如何扩展一个实体框架6.1.3生成的类? [英] How to extend an Entity Framework 6.1.3 generated class?
问题描述
是否可以扩展实体框架6.1.3生成的类?
Is it possible to extend an Entity Framework 6.1.3 generated class?
我有一个现有的数据库,我已经创建了一个ADO.NET实体数据模型, Visual Studio 2015依次生成了一组类。
I have an existing database to which I have created an ADO.NET Entity Data Model, which in turn Visual Studio 2015 has generated a set of classes.
public partial class WebApplication1Entities : DbContext
{
public WebApplication1Entities()
: base("name=WebApplication1Entities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
}
我可以手动覆盖WebApplication1Entities以允许动态运行时连接如下:
I can manually override the WebApplication1Entities to allow a dynamic runtime connection as so:
public WebApplication1Entities(string connectionString) : base(connectionString)
{
}
然而,这涉及编辑Visual Studio 2015生成的类,但是我希望更新ADO .NET实体数据模型在将来,Visual Studio将覆盖我对上一个生成的类进行的任何手动更改,而且我已经回到第一个方法,必须手动编辑生成的类。
This however, involves editing the class that Visual Studio 2015 has generated, but should I wish to update the ADO.NET Entity Data Model in the future, Visual Studio will overwrite any manual changes I have made to the previous generated class and I'm back to square one, having to manually edit the generated class.
是否可以创建一个帮助类或类似的扩展现有的 WebApplication1Entities:DbContext
,并允许添加新的重载方法,并继承Visual Studio 2015生成的类的现有方法,如虚拟DbSets。
Is it possible to create a helper class or something similar to extend the existing WebApplication1Entities : DbContext
, and allow the addition of the new overloaded method and also inherit the existing methods of the Visual Studio 2015 generated class such as virtual DbSets.
任何帮助将不胜感激: )
Any help would be much appreciated :-)
推荐答案
正如您在声明中所看到的那样,
As you see in the declaration
public partial class WebApplication1Entities : DbContext
这个类是部分
。
所以你可以创建另一个* .cs文件,并将你的代码放在那里(使用相同的命名空间!):
So you can create another *.cs file and put your code there (use the same namespace!):
public partial class WebApplication1Entities
{
public WebApplication1Entities(string connectionString) : base(connectionString)
{
}
}
所以当设计师覆盖该文件包含原始类,您的代码保持不变。
So when the designer overwrites the file containing the "original" class, your code stays untouched.
更多关于 partial
类和方法。
这篇关于如何扩展一个实体框架6.1.3生成的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!