使用数据库优先方法时重写或替换默认构造函数

本文关键字:重写 替换 默认 构造函数 方法 数据库 | 更新日期: 2023-09-27 18:32:16

我们使用数据库优先方法来创建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>();
    }
}

使用数据库优先方法时重写或替换默认构造函数

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

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

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

现在在您自己的分部类中:

partial class Product
{
    partial void Initialize()
    {
        this.Unit = 1; // or whatever.
    }
}

与完全重写默认构造函数相比,优点是可以保留 EF 的初始化代码。

您所见,EF 生成的类是 public **partial** class . 因此,创建一个新类并将您的代码添加到其中。只需确保它与 EF 生成的文件具有相同的命名空间

//EF Generated
public partial class Product
{
}
//Custom class
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>();
    }

我可能应该提到您的自定义类也应该在一个单独的文件中。 我通常在与 edmx 文件相同的目录中创建一个元数据文件夹,然后在那里添加我的部分类