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?

3
  • 3
    You should use code-first approach, which you can control your model classes instead of letting EF generates models for you from database Commented Jun 18, 2013 at 14:28
  • 3
    You can update the T4 template to generate the code you want. Commented Jun 18, 2013 at 18:48
  • Cuong Le, Pawel, Thank you. Finally I've decided to use CodeFirst and now everything is ok with inheritance. Commented Jun 19, 2013 at 13:48

1 Answer 1

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"
Sign up to request clarification or add additional context in comments.

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.