Question

I want to store some objects where there is exactly one Bar for each Foo.

I have some POCO objects that look something like this:

public class Foo
{
    public int Id { get; set; }
    public string FooProperty { get; set; }
    public int BarId { get; set; }
    public virtual Bar Bar { get; set; }
}
public class Bar
{
    public int Id { get; set; }
    public string BarProperty { get; set; }
    public int FooId { get; set; }
    public virtual Foo Foo { get; set; }
}

The Foo and Bar have a 1:1 relationship, and based on the reading I've done I tried the following in my DbContext class:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
    modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();

    modelBuilder.Entity<Foo>()
                   .HasRequired(x => x.Bar)
                   .WithRequiredPrincipal(x => x.Foo);

    base.OnModelCreating(modelBuilder);
}

The backing store is SQL Server, and this does indeed create me tables with a 1:1 relationship. However, the FK relationship from Bar to Foo is on the Id field of both tables, whereas I would expect it to be from the FooId field of the Bar table to the Id field of the Foo table.

It seems that EF has decided to keep the PK (Id) field of both tables in sync, and is essentially ignoring my BarId/FooId columns.

What am I doing wrong?

Was it helpful?

Solution

Are you sure you want a 1:1 relationship? If for every foo there is a single bar, and every bar there is a single foo, EF will use the primary keys for the relationship, and it probably should. Are you sure you don't want a 1:many or 1:0..1 relationship?

If you want a Foo to be able to have many bars, so you can define a FK you could change your fluent:

  modelBuilder.Entity<Foo>()
                .HasRequired(x => x.Bar)
                .WithMany()
                .HasForeignKey(f => f.BarId);

Here's a blog post about One-To-One foreign key relationships which might help

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top