将行为注入我的所有实体的最有效方法是什么?
我正在将大型数据模型从旧的 Microsoft 数据访问库转换为 Entity Framework 4。我想将这两种方法“注入”到大多数(如果不是全部)从现有数据库生成的实体中我的 EF 模型:
public bool Deleted
{
get { return this.EntityState == System.Data.EntityState.Deleted; }
set
{
if (value)
Context.DeleteObject(this);
}
}
public bool Inserted
{
get { return this.EntityState == System.Data.EntityState.Added; }
set
{
if (value)
Context.AddObject(this.GetType().Name, this);
}
}
与其为每个实体(有超过 100 个)创建一个分部类,不如将这些方法添加到模型中的所有实体中更好的方法是什么?
预先感谢您的建议。
I'm converting a large data model from an old Microsoft data access library to Entity Framework 4. I'd like to "inject" these two methods into most, if not all, of the entities that have been generated from the existing database into my EF model:
public bool Deleted
{
get { return this.EntityState == System.Data.EntityState.Deleted; }
set
{
if (value)
Context.DeleteObject(this);
}
}
public bool Inserted
{
get { return this.EntityState == System.Data.EntityState.Added; }
set
{
if (value)
Context.AddObject(this.GetType().Name, this);
}
}
Rather than creating a partial class for each entity (there are over 100), what's the better way to add these methods to all the entities in the model?
Thanks in advance for your suggestions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我将修改 EF T4 模板以自动生成这些属性。
I'd modify the EF T4 template to generate these properties automatically.
扩展@Daz(有点稀疏)的答案:右键单击设计器并选择
添加代码生成项...
,然后选择ADO.NET 实体对象生成器。
它将创建一个模板,该模板生成与编译器已创建的代码完全相同的代码,然后您可以对其进行自定义。打开它,很容易看到如何修改它。它的设计正是为了您所描述的目的。这是一篇最近的 MSDN 文章,详细描述了一些事情。
Expanding on @Daz's (somewhat sparse) answer: Right-click in the designer and select
Add Code Generation Item...
, thenADO.NET Entity Object Generator.
It will create a template that generates exactly the same code that the compiler already creates, which you can then customize. Open it up, it's pretty easy to see how to modify it. It's designed for exactly the purpose you describe.Here's a recent MSDN article describing things in detail.
为您的实体创建一个新的基类,它应该继承您正在使用的当前基类,并使用该代码扩展其成员。
Create a new base class for your entities, it should inherit the current one you are using and extend its members with that code.
扩展方法可以解决问题。但当然它们是方法,而不是像您在示例中所做的那样的正确属性(框架中尚不存在扩展属性,仅存在扩展方法)。
毫无疑问,这个解决方案是最优雅的,也是最接近您的需求的。无需接触代码生成,也无需在所有类上复制相同的代码。如果这些方法必须发生某些变化,则更改将在一个地方完成,您的所有类都将从中受益。
Extension methods do the trick. But of course they are methods, not proper properties like you make in your sample (extension properties don't exist yet in the framework, only extension methods).
Undoubtly this solution is the most elegant and the nearest from your demand. No need to touch the code generation nor to duplicate the same code on all your classes. If something has to evolve in these methods, the changes will be done in one single place and all your classes will take benefit from it.