使用数据库优先方法时覆盖或替换默认构造函数 [英] Override or replace default constructor when using database first approach

查看:92
本文介绍了使用数据库优先方法时覆盖或替换默认构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

We are using the database first approach to creating our MVC models, which means the framework auto-generates a default constructor in the primary .cs file. I have a couple default values that I'd like to set, however, and the problem is this framework generates a basic .cs file for this model each time the .edmx is updated. Is there any way to either override this constructor in something like a partial 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>();
    }
}

推荐答案

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

You could edit the t4 template that generates the classes to make it generate a partial method that is called in the parameterless constructor. Then you can implement this method in an accompanying partial class.

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

After editing, your generated code should look like this:

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

partial void Initialize();

现在在您自己的局部课程中:

Now in your own partial class:

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

完全覆盖默认构造函数的好处是,您可以保留EF的初始化代码.

The advantage over completely overriding the default constructor is that you keep EF's initialization code.

这篇关于使用数据库优先方法时覆盖或替换默认构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆