类可以继承实体框架类并仍然使用继承的类映射保留回数据库吗?
类可以继承实体框架类并仍然使用继承的类映射保留回数据库吗?当我尝试从“自我跟踪实体”类派生时,我收到错误,并指出该类型没有任何映射。我本来希望,由于类型是从实体类继承的,因此它也可以以某种方式继承实体映射以使其正常工作。有人能够让它发挥作用吗?
我试图支持的方案是在另一个引用包含实体和映射的程序集的程序集中扩展实体对象。部分类和映射被编译到包含实体对象的程序集中。所以我无法通过使用部分类来实现这一点。
Can a class inherit from Entity Framework class and still persist back to the DB using the inherited classes mappings? I have received errors trying to derive from a 'Self-Tracking Entity' class when I try and SaveChanges stating that the Type does not have any mappings. I would have hoped since the Type was Inherited from the Entity class that it could also inherit the entity mappings somehow for this to work. Has anyone been able to get this to work?
The scenario I am trying to support is to extend the Entity object in another assembly that references the assembly containing the Entity's and mappings. Partials classes and mappings are compiled into the assembly containing the Entity objects. So I can't accomplish this through the use of partial classes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,EDMX(和自我跟踪实体)不可能。如果要存储派生类型,也必须对其进行映射。如果您需要向生成的代码添加任何内容,请使用您自己的实体类的部分部分。
令人惊讶的是,代码优先(EFv4.1 和 DbContext API)似乎可以实现,但在这种情况下,您无法使用自我跟踪实体。我刚刚检查了数据库,代码优先是不可能的以及。它默默地创建 TPH 继承,并将派生类映射为另一个实体。No it is not possible with EDMX (and self tracking entities). If you want to store derived type it must be mapped as well. If you need to add anything to generated code use your own partial part of the entity class.
Surprisingly it looks like it is possible with code-first (EFv4.1 and DbContext API) but in such case you cannot use self tracking entities.I just checked database and it is not possible with code-first as well. It silently creates TPH inheritance and derived class is mapped as an another entity.除非您确实需要覆盖某些数据或默认功能,否则最好的选择是扩展该类。由于 EF 类被声明为
partial
,因此您可以创建另一个代码文件并将自定义方法或属性放入其中。然后,您将获得所有对象持久性以及自定义代码。编辑 - 为了响应您的澄清,如果您需要修改另一个程序集中的 EF 类,不幸的是,您最好的选择是创建一个将 Entity 类作为成员的包装类。然后,您将编写所有新功能来访问装箱实体的公共部分。它不会让你对新属性产生持久性,但无论如何你都没有得到它。
Unless you really need to override some of the data or default functionality, your best bet is to just extend the class instead. Since the EF classes are declared as
partial
, you can create another code file and drop your custom methods or properties in that. Then, you get all the object persistence as well as your custom code.Edit -- In response to your clarification, your best bet if you need to modify an EF class in another assembly is unfortunately to create a wrapper class that takes an Entity class as a member. You would then write all the new functionality to access the boxed Entity's public pieces. It won't give you persistence for the new properties, but you weren't getting that anyway.