I have been struggling for a while now to convert a fairly large EntityFramework database created in model first to codefirst. I have a problem that I cant seem to resolve. I am getting an Object reference not set to an instance of an object with the following procedures on the call stack.
ModelConfiguration.Configuration.Types.EntityTypeConfiguration.Configure
ModelConfiguration.Configuration.ModelConfiguration.ConfigureEntities
to simplify the post I have created a test project that boils the problem down to its simplest form.
I have 3 classes
- a which has an has an optional b and an optional c
- b which has a collection of a's, and a colleciton of c's
c which has an optional b and a collection of a's
public class a { public int Id { get; set; } [Required] public string name { get; set; } public virtual b b { get; set; } [ForeignKey("b")] public int? b_Id { get; set; } public virtual c c { get; set; } [ForeignKey("c")] public int? c_Id { get; set; } } public class b { public int Id { get; set; } public string name { get; set; } public virtual ICollection<a> a_s { get; set; } public virtual ICollection<c> c_s { get; set; } } public class c { public int Id { get; set; } public virtual b b { get; set; } [ForeignKey("b")] public int? b_Id { get; set; } public virtual ICollection<a> a_s { get; set; } } public class MyContext : DbContext { public DbSet<a> a { get; set; } public DbSet<b> b { get; set; } public DbSet<c> c { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<a>() .HasOptional(m => m.b) .WithMany(m => m.a_s); modelBuilder.Entity<b>() .HasMany(m => m.c_s) .WithRequired(m => m.b); modelBuilder.Entity<c>() .HasMany(m => m.a_s) .WithOptional(m => m.c); base.OnModelCreating(modelBuilder); } }when I execute the code var a = from o in db.a select o, I get the error described above. There is absolutely no information on what is hapenning, so I really dont know where to turn. Can anyone help me solve this problem, as I really want to move away from Model First.
namespace MvcApplication2.Controllers { public class HomeController : Controller { public ActionResult Index() { var db = new MyContext(); var a = from o in db.a select o; return View(); } } }