Handling class inheritance using Code First RRS feed

  • Question

  • Say, I've got 3 kinds of accounts in my system: Teacher, Student and Administrator. And I also got 3 tables in database for them: Teacher, Student and Administrator. They all share a portion of common fields, such as UserName, PhoneNumber, Email etc. Instead of defining these fields repeatedly in 3 classes, I want to create an ABSTRACT AccountBase class to hold these common fields. Hence I have the following requirements for Entity Framework:

    1. AccountBase should not be mapped to database table as there'll be no AccountBase table. That is to say, AccountBase has no business meaning at all and is simply my own way of saving time for coding and unit testing those commonplace property definitions.
    2. I have the Privilege requirement. Administrator account's privilege is account-specific, while Teacher and Student account's privilege is role-specific. That's to say, in Administrator, I would have an ICollection<Privilege> property directly; while in Teacher and Student I would define a RoleId and Role navigation property, which in turn associates with Privilege objects. In database, there'll be an AdministratorPrivilege table and a RolePrivilege table to fulfill this requirement.

    The POCO classes for Administrator, Teacher and Student are too straightforward to deserve pasting here. I just want to know how to tell Entity Framework to build the mappings based on my aforementioned requirements.

    Thanks much for any help.


    You Can't Stop Me!
    Tuesday, July 26, 2011 3:46 PM


All replies

  • Hi,

    the following topic describes different inheritance mapping scenarios:


    thank you,


    This posting is provided "AS IS" with no warranties, and confers no rights.
    • Marked as answer by buaaytt Monday, August 1, 2011 2:39 AM
    Tuesday, July 26, 2011 6:44 PM
  • Thanks Julia, for pointing me out the concepts of different mapping types.

    While TPC may be the most appropriate solution for me, I ended up with a small trick, which is not to include the AccountBase in my context, to achieve the goal of not mapping the AccountBase table. I can't mark AccountBase [NotMapped] because that would make all my subclasses not able to map either.

    You Can't Stop Me!
    Monday, August 1, 2011 2:39 AM