0

Say I have an abstract Person Table, and derived tables, Student and Teacher, Admin etc. Person has a enum property PersonType with values for each derived class, and a virtual collection Events.

Now when Entity Framework creates the Events table, it creates a column for each class derived from Person, eg. Student_Id, Teacher_Id, Admin_Id etc.

If I have a dozen derived classes, then that's a dozen extra columns, only 1 of which is ever in use.

How do I tell Entity Framework to instead refer to the PersonType property in conjunction with the Id instead of creating all these unnecessary columns?

ecairncross
  • 41
  • 1
  • 5
  • This link helped me a lot with doing something like this: [Understanding Inheritance in Entity Framework](http://www.dotnet-tricks.com/Tutorial/entityframework/KP45031213-Understanding-Inheritance-in-Entity-Framework.html) – Ron Beyer Dec 09 '15 at 18:02

1 Answers1

0

So it has simple solution with DataAnnotations, if i understood you correctly.

[Column("TableID")]

I'm going to give you a working example from a project of mine. So i have an abstract Class which has called Trip. Cruise and Hotel classes are derived from Trip class. I need to Store Comments on a single table and as you have concerned i dont need CruiseID nor HotelID on Comments table so i named TripID with Column Annotation and entity framework will create table magically if we annotated well

public class Comment
{
     public int CommentID { get; set; }
     [Column("TripID")]
     [ForeignKey("Trip")]
     public int TripID { get; set; }
     public virtual Trip Trip { get; set; }
     public string Text { get; set; }
}

public class CruiseComment : Comment
{
    [Column("TripID")]
    [ForeignKey("Cruise")]
    public int CruiseID { get; set; }
    public virtual Cruise Cruise { get; set; }

}

public class HotelComment : Comment
{
    [Column("TripID")]
    [ForeignKey("Cruise")]
    public int HotelID { get; set; }

    public virtual Hotel Hotel { get; set; }
}

It's not necessary to use ForeignKey annotation. It's needed when you have different namings.

c0demaster
  • 738
  • 6
  • 17