扩展实体框架模型以包含新属性
我是 EF 的新手,所以如果这是一个菜鸟问题,请原谅我。
基本上,我们使用 Model First 为我们的“平台”项目设置了一个 EF 模型,并在我们在此平台上构建的许多应用程序之间共享。在其中一些应用程序中,我们希望扩展类以包含其他属性,而不更改平台中的模型。这对于 EF 4 是否可行?在不修改 .edmx 文件的情况下如何才能做到这一点?
我注意到生成的类都是部分的,因此我可能可以创建一个具有相同名称的新的部分类来包含新属性,但是是否有任何映射需要处理?
ps 在正常情况下,我更愿意使用继承并创建一个新类来保存新属性,但同样,我不知道如何使用 EF 来做到这一点..这里的任何启发将不胜感激!
非常感谢,
I'm new to EF so please excuse me if this is a noob question.
Basically, we have a EF model set up using Model First for our 'platform' project and is shared across many applications which we build on top of this platform. In some of these applications we want to extend the classes to include additional properties without changing the model in the platform. Is this possible with EF 4 and how would I be able to do it without modifying the .edmx file?
I notice that the generated classes are all partial so potentially I could create a new partial class with the same name to include the new properties but is there any mappings that need to be taken care of?
p.s. under normal circumstances I'd have preferred to use inheritance and create a new class to hold the new properties instead but again, I don't know how to do that with EF.. any enlightenment here will be much appreciated!
Many thanks,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不能使用继承,因为一旦从数据源加载实体,EF 将不知道继承,因此它将实例化没有您的属性的基类型,而不是具有您的属性的派生类型。如果 EF 必须使用任何继承,则必须在 EDMX 中映射任何继承。
使用分部类可以解决您的问题,但是:
You cannot use inheritance because once entity is loaded from the data source EF will not know about inheritance and because of that it will instantiate base type without your properties instead of derived type with your properties. Any inheritance must be mapped in EDMX if EF have to work with it.
Using partial class will solve your problem but:
EF 生成部分类。因此,要扩展 MyEntity,请使用
edit: 在与生成的实体相同的命名空间中创建一个 MyEntity.cs 文件
EF generates partial classes. So to extend MyEntity, create a MyEntity.cs file with
edit: in the same namespace as your generated entities
我同意向您的实体的部分类添加额外的属性(正如您和 Kaido 所说)。
这样您就可以自由添加所需的属性,而无需修改生成的类,并且如果您再次生成模型(或从数据库更新它),您的部分类不会被修改。
在我看来,向生成实体的部分类添加属性是正确的方法。
I agree with adding additional properties to partial class of your entities (as you and Kaido said).
This way you can freely add the properties you want, without modifying generated classes and if you generate your model again (or update it from DB), your partial class is not modified.
In my opinion, adding properties to partial classes of generated entities is the way to go.