2011-06-30 44 views
0

我有兩個集合。父母有很多孩子,但也存儲最新的孩子的ID。如何映射此導航屬性?

public class Foo 
{ 
    public int Id { get; set; } 
    public ICollection<Bar> Bars { get; set; } 

    public int? CurrentBarId { get; set; } 

    // adding this causes the error below 
    public virtual CurrentBar CurrentBar { get; set; } 
} 

public class Bar 
{ 
    public int Id { get; set; } 
    public int FooId { get; set; } 
    public virtual Foo Foo { get; set; } 
} 

當我加入CurrentBarId財產一切都正確地持久。但是,當我添加CurrentBar屬性時,創建時引發異常。

我得到異常:

{"Invalid column name 'Foo_Id'."} 

我該如何映射在此背景下導航屬性?

更新

我已經打得四處這一點,並結束了:

modelBuilder.Entity<Foo>() 
    .HasOptional(x => x.CurrentBar) 
    .WithOptionalDependent() 
    .Map(map => 
    { 
     map.ToTable("Bar").MapKey("CurrentBarId"); 
    }); 

現在,我得到了下面的錯誤。這是正確的方向,或者我應該如何努力做到這一點?

錯誤3034:在映射問題 片段起始於線213, 442:從一個EntitySet的一個實體被 映射到也可以映射到 一個實體與另一個的EntitySet與 可能不同的鍵的行。確保這兩個映射片段不會將兩個 不相關的EntitySets映射到兩個重疊的行羣組 。

回答

1

假設Foo.BarsBar.Foo是相同的關係的端部和CurrentBar是的第二關係一端,我會嘗試這樣的:

modelBuilder.Entity<Foo>() 
    .HasMany(f => f.Bars) 
    .WithRequired(b => b.Foo) 
    .HasForeignKey(b => b.FooId) 
    .WillCascadeOnDelete(false); 

modelBuilder.Entity<Foo>() 
    .HasOptional(f => f.CurrentBar) 
    .WithMany() 
    .HasForeignKey(f => f.CurrentBarId) 
    .WillCascadeOnDelete(false); 

這將創建一個(可爲空的)CurrentBarId FK Foos表中的列和Bars表中的(不可爲空的)FooId FK列。

+0

有趣的是,我沒想到會使用HasMany。它看起來像工作,謝謝一堆! – blu