如何在Entity Framework中创建1:1关系?

时间:2012-08-06 15:58:47

标签: entity-framework ef-code-first entity-framework-ctp5

我想存储一些对象,其中每个Foo只有一个Bar。

我有一些看起来像这样的POCO对象:

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

Foo和Bar有一个1:1的关系,根据我已经完成的阅读,我在DbContext类中尝试了以下内容:

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

后备存储是SQL Server,这确实创建了具有1:1关系的表。 但是,从BarFoo的FK关系位于两个表的Id字段上,而我希望它来自FooId } Bar表的字段到Id表的Foo字段。

似乎EF决定保持两个表的PK(Id)字段同步,并且基本上忽略了我的BarId / FooId列。

我做错了什么?

1 个答案:

答案 0 :(得分:3)

你确定你想要1:1的关系吗?如果对于每个foo都有一个单独的条,并且每个条都有一个foo,EF将使用主键进行关系,它可能应该。你确定你不想要1:多或1:0..1的关系吗?

如果你想要一个Foo能够有很多小节,那么你可以定义一个FK你可以改变你的流利:

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

这是一篇关于One-To-One foreign key relationships的博文,可能会有所帮助