Thursday, May 30, 2013

How to solve "null reference exception" problem when turn off ProxyCreationEnabled in Code first Entity framework?

If turn on lazy loading in entity framework by:
Configuration.ProxyCreationEnabled = false;
Will get null reference exception problem when try to get navigation properties.

Need to do eagerly loading for navigation property by include clause
using (var context = new BloggingContext())
{
    // Load all blogs and related posts
    var blogs1 = context.Blogs
                          .Include(b => b.Posts)
                          .ToList();

}

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