I need to have a reference table to combine these two entities. I have built the following table, and unfortunately it is not working. Is there an easier way of doing this? Or can someone please explain why the entity will keeps throwing a null reference error, when I try and create it in the controller?
public class BridgeTable
{
[Key, Column(Order = 0)]
public int Entity1ID { get; set; }
[Key, Column(Order = 1)]
public string Entity2ID { get; set; }
[Required]
public virtual Entity1 entity1 { get; set; }
[Required]
public virtual Entity2 entity2 { get; set; }
}
public class Entity1
{
public int ID { get; set; }
…
public virtual List<BridgeTable> bridgeTable { get; set; }
}
public class Entity2
{
public int ID { get; set; }
…
public virtual BridgeTable bridgeTable { get; set; }
}
My model builder:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<BridgeTable>().HasRequired<Entity2>(e => e.bridgeTable).WithRequiredDependent();
base.OnModelCreating(modelBuilder);
}
Throws this exception:
Object reference not set to an instance of an object.
In my controller post method:
BridgeTable bridgeTable = new BridgeTable {
public DbSet<Entity1> entity1{ get; set; }
public DbSet<BridgeTable> bridgeTable { get; set; }
public DbSet<Entity2> entity2 { get; set; }