2012-08-06 94 views
0

我想存储一些对象,每个Foo只有一个Bar。如何在实体框架中创建1:1关系?

我有一个看起来像这样一些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和酒吧有一个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领域,而我希望它是从Bar表的FooId领域的Foo表的Id领域。

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

我在做什么错?

回答

3

您确定要1:1关系吗?如果每个富都有一个单独的酒吧,并且每个酒吧都有一个单独的富豪,那么EF将使用主要关键字,并且可能应该这样做。你确定你不想要1:多或1:0..1的关系吗?

如果你想有一个富到能有很多酒吧,所以你可以定义FK你可以改变你的流利:

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

这里有一个博客帖子大约One-To-One foreign key relationships这可能有助于

+0

感谢。我确实需要1:1,并且我想共享PK是可以的。我将FooId/Foo和BarId/Bar属性添加到我的POCO对象的原因是因为根据我读过的“如何”文章推荐这样做。它在1:很多情况下都有效,而且看起来有些奇怪,因为它们是1:1而不具备这些参数。我认为代码优先的东西是为了在很大程度上消除后备存储和对象之间的耦合... – 2012-08-06 16:30:26