使用数据库第一种方法时覆盖或替换默认构造函数

Nea*_*alR 2 c# asp.net-mvc entity-framework asp.net-mvc-4

我们使用数据库第一种方法来创建我们的MVC模型,这意味着框架在主.cs文件中自动生成默认构造函数.但是,我有一些我想设置的默认值,问题是这个框架每次.edmx更新时都会为此模型生成一个基本的.cs文件.有没有办法在部分类中覆盖这个构造函数?

public partial class Product
{
    // The framework will create this constructor any time a change to 
    // the edmx file is made. This means any "custom" statements will 
    // be overridden and have to be re-entered
    public Product()
    {
        this.PageToProduct = new HashSet<PageToProduct>();
        this.ProductRates = new HashSet<ProductRates>();
        this.ProductToRider = new HashSet<ProductToRider>();
    }
}
Run Code Online (Sandbox Code Playgroud)

Ger*_*old 6

您可以编辑生成类的t4模板,以使其生成在无参数构造函数中调用的部分方法.然后,您可以在附带的分部类中实现此方法.

编辑后,生成的代码应如下所示:

public Product()
{
    this.PageToProduct = new HashSet<PageToProduct>();
    this.ProductRates = new HashSet<ProductRates>();
    this.ProductToRider = new HashSet<ProductToRider>();
    Initialize();
}

partial void Initialize();
Run Code Online (Sandbox Code Playgroud)

现在在你自己的部分课程中:

partial class Product
{
    partial void Initialize()
    {
        this.Unit = 1; // or whatever.
    }
}
Run Code Online (Sandbox Code Playgroud)

完全覆盖默认构造函数的优点是保留EF的初始化代码.