How to extend an Entity Framework 6.1.3 generated class?(如何扩展 Entity Framework 6.1.3 生成的类?)
问题描述
是否可以扩展 Entity Framework 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 :-)
推荐答案
正如你在声明中看到的
public partial class WebApplication1Entities : DbContext
这个类是partial
.
因此您可以创建另一个 *.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
类和方法.
这篇关于如何扩展 Entity Framework 6.1.3 生成的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何扩展 Entity Framework 6.1.3 生成的类?


- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- C# 中多线程网络服务器的模式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01