NealR
NealR

Reputation: 10669

Override or replace default constructor when using database first approach

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?

Example

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>();
    }
}

Upvotes: 2

Views: 3202

Answers (2)

Gert Arnold
Gert Arnold

Reputation: 109079

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.
    }
}

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

Upvotes: 7

JamieD77
JamieD77

Reputation: 13949

as you can see the class that EF generates is public **partial** class. So create a new class and just add your code to it. Just make sure it has the same namespace as the EF generated file

//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>();
    }

I should probably mention that your custom class should also be in a separate file.. I usually create a Metadata folder in the same directory as the edmx file and just add my partial classes in there

Upvotes: -1

Related Questions