Jude Jude - 3 months ago 11
ASP.NET (C#) Question

Updating From Database Causes Redoing The Inheritance

Using EF 5. Below is Model.cs file under the Model.tt
I was suggested to have an interface to be inherited by all the entities on the model for some reason. You see the two of them (Adress, Kids) below.

public interface IHasAutoID
{
int getAutoId();
}

public partial class Adress : IHasAutoID
{
public int ID { get; set; }
public Nullable<System.DateTime> date{ get; set; }
..
..
}

public partial class Kids : IHasAutoID
{
public int ID { get; set; }
public Nullable<System.DateTime> date { get; set; }
..
}


Whenever I "Update Model From Database", as the "Tables" are not selectable(I don't know why), I need to delete the whole model and create new connection to the database. No problem at all. But this causes interface inheritance goes missing. every time I need to inherit all entities(almost 50) from "IHasAutoID" interface. I need your expertise.

Answer

You can create separate partial classes that contain your customizations. This is how I would do it (assuming that each class has public int ID):

public interface IHasAutoID
{
    int ID { get; set; }
    int GetAutoId();
}


public partial class Address : IHasAutoID
{
    public int GetAutoId()
    {
         return this.ID;
    }
}

Note that this is a class beside the Address class generated by EF. By using an interface you have to implement the GetAutoId() in each partial class. An alternative could be to do this in an abstract base class. Personally, I prefer interfaces despite the larger amount of boilerplate code. Inheritance often complicates code more than necessary.

A third alternative is to modify the t4 template to include the interface and its implementation in the generated code. It's not too hard. (But it usually takes some trial and error).

One last comment: you apparently want get generated ID values. But these values are returned into new entities after EF executes SaveChanges, maybe you don't even need this interface?