Thursday, May 30, 2013

Inheritance in Entity Framework Code First

public abstract class Person
{
     public int PersonID { get; set; }
     public string Name { get; set; }
}
 
public class StaffMember : Person
{
     public string BadgeNumber { get; set; }
     [ForeignKey("StaffMemberID")]
     public virtual ICollection Appointments { get; set; }
}
 
public class Client : Person
{
     [ForeignKey("ClientID")]
     public virtual ICollection Appointments { get; set; }
}
 

public class MyContext : DbContext
{
     public DbSet People { get; set; }
     protected override void OnModelCreating(DbModelBuilder modelBuilder)
     {
          base.OnModelCreating(modelBuilder);
     }
 
     public void Seed(MyContext context)
     {
          Client c1 = new Client { Name = "Steve Client" };
          StaffMember sm1 = new StaffMember { Name = "Staff 1", BadgeNumber = "1234" };
          StaffMember sm2 = new StaffMember { Name = "Staff 2", BadgeNumber = "5678" };
 
          context.People.Add(c1);
          context.People.Add(sm1);

          context.SaveChanges();
      }
 
      public MyContext()
      {
           Database.SetInitializer(new DropCreateDatabaseAlways());
           this.Seed(this);
      }
}


http://sgordondeveloper.blogspot.ca/2013/02/model-inheritance-with-relationship-in.html

No comments:

Post a Comment