I can't seem to get the relationship between Foo and Bar right.
public class Foo
{
[Key]
public int Id { get; set; }
public int Name { get; set; }
public virtual Bar Bar { get; set; }
}
public class Bar
{
[Key]
public int Id { get; set; }
public int Name { get; set; }
public int FooId { get; set; }
public virtual Foo Foo { get; set; }
}
With this structure I would normally have
public virtual ICollection<Bar> Bars { get; set; }
in Foo, but in this instance, that isn't a workable representation of my data.
You see....
Foo won't always have a Bar ...but... Bar will always have a Foo and its FooId will always be unique across Bar.
public class MyContext : DbContext
{
public DbSet<Foo> Foos { get; set; }
public DbSet<Bar> Bars { get; set; }
protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// ...............
modelBuilder.Entity<Foo>()
.HasOptional(cpi => cpi.Bar)
.WithRequired(api => api.Foo);
// ...............
}
}
I have tried multiple attempts at defining the relationship, but can't seem to get it right! I also could add a nullable BarId to Foo if that would enable me to do what I want (but I would prefer not to). (see edit 1)
I have googled it lots (and searched through, and tried), many stack overflow posts that were similar (but not the same).
Any input would be appreciated.
Thanks
Edit 1 (in response to spenders comment):
These tables already exist in a number of live environments and are full of data so I would like to find a solution without editing the db table definitions... but if that is not possible I can add a column to achieve what I need.
Previously I had it defined as...
public virtual ICollection<Bar> Bars { get; set; }
... but that won't work for a piece of code I am writing using these tables.
Edit 2:
The above code gives the following error when I try and add a Bar.
"Cannot insert explicit value for identity column in table 'Bar' when IDENTITY_INSERT is set to OFF."
Identity insert is not turned off, I use it for all tables, except in this instance where EF seems to be turning it off based on my definition of these tables.