2012-08-06 93 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