Kevin
Kevin

Reputation: 127

EntityFramework Object Not Set to Instance of Object in Model Creation

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

Upvotes: 0

Views: 4054

Answers (2)

Memet Olsen
Memet Olsen

Reputation: 4608

Try putting 'a' into local memory:

var a = from o in db.a.ToList() select o;

Upvotes: 1

Eranga
Eranga

Reputation: 32447

The mixup of fluent configuration and data annotation caused this problem. EF team should have handled this exception and given a meaningful error message.

Remove data annotations and use fluent configuration as follows

public class a
{
    public int Id { get; set; }

    [Required]
    public string name { get; set; }

    public virtual b b { get; set; }

    public int? b_Id { get; set; }

    public virtual c c { get; set; }

    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; }

    public int? b_Id { get; set; }

    public virtual ICollection<a> a_s { get; set; }
}

public class NreContext : 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)
            .HasForeignKey(m => m.b_Id);

        modelBuilder.Entity<a>()
            .HasOptional(m => m.c)
            .WithMany(m => m.a_s)
            .HasForeignKey(m => m.c_Id);

        modelBuilder.Entity<c>()
            .HasOptional(m => m.b)
            .WithMany(m => m.c_s)
            .HasForeignKey(m => m.b_Id);

        base.OnModelCreating(modelBuilder);
    }
}

Upvotes: 3

Related Questions