2

I am using Entity Framework Database First for working with db.

I have a base class EntityBase

public class EntityBase
{        
    public Int32 Id { get; set; }
}

I have some other classes that are generated by EnitytFramework and represents tables of my db, for example, "User" class:

public class User
{
  public int32 Id{get;set;} 
  public class Name{get;set;}
  public class Age{get;set;}
}

I want all EF model classes to be inherited from EntityBase:

public class User : EntityBase

I can do this manually, by deleting Id field from User class and defining inheritance, but after I am updating model from db, all manually-made changes dissapears. Is there any way to keep or automatically add inheritance to EF model classes?

Iliya Krinchiyan
  • 267
  • 5
  • 14

1 Answers1

4

EF database first work with t4 files if you change manually the class, save and compile, T4 will generate the classes again and you lose your changes. You must make this change in T4 template. Search the EntityClassOpening method and change the last line:

_typeMapper.GetTypeName(entity.BaseType)

with this code:

_typeMapper.GetTypeName(entity.BaseType) ?? "EntityBaseClass"
  • Hi José, could you advise how to make the T4 not generate properties of base class? I get the warning "GeneratedEntity.ID hides inherited member EntityBaseClass.ID" – Khoait Jun 17 '16 at 10:30
  • This is not a problem of EF this is a problem of inheritance, if you have already declared an id in the base class you should use it, otherwise eliminate the inheritance to the base class. –  Jun 20 '16 at 01:19