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 生成的类?
基础教程推荐
- 将 XML 转换为通用列表 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- MS Visual Studio .NET 的替代品 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01