0

同一I類具有在它自身具有ParentDiscussion和TopParentDiscussion討論對象:2屬性指向在EF代碼首先

public class Discussion 
    { 
     [Key] 
     public Guid ID { get; set; } 
     public String Message { get; set; } 
     public virtual Discussion ParentDiscussion { get; set; } 
     public virtual Discussion TopParentDiscussion { get; set; } 

    } 

Parent和TopParent是可選的。我用Fluent API編寫了以下情況,並且工作正常。

 modelBuilder.Entity<Discussion>().HasOptional<Discussion>(a => a.ParentDiscussion).WithOptionalDependent().Map(a => a.MapKey("TopParentId")); 
     modelBuilder.Entity<Discussion>().HasOptional<Discussion>(a => a.TopParentDiscussion).WithOptionalDependent().Map(a => a.MapKey("ParentId")); 

但是我怎麼能寫這個解決方案沒有流利的API,所以數據註釋。

我嘗試這樣做:

 //Foreign Keys 
     public Guid? ParentId { get; set; } 
     public Guid? TopParentId { get; set; } 

     //Relationships 

     [ForeignKey("ParentId")] 
     public virtual Discussion ParentDiscussion { get; set; } 
     [ForeignKey("TopParentId")] 
     public virtual Discussion TopParentDiscussion { get; set; } 

但它給我下面的錯誤:

Unable to determine the principal end of an association between the types 'Model.Discussion' and 'Model.Discussion'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations. 

回答

0

不能映射這與數據註解,因爲你不公開外鍵屬性和反向導航屬性。

用流利的API正確的映射是:

modelBuilder.Entity<Discussion>() 
      .HasOptional<Discussion>(a => a.ParentDiscussion) 
      .WithMany() 
      .Map(a => a.MapKey("TopParentId")); 
modelBuilder.Entity<Discussion>() 
      .HasOptional<Discussion>(a => a.TopParentDiscussion) 
      .WithMany() 
      .Map(a => a.MapKey("ParentId")); 

因爲你想可能要討論更然後另一個討論的父母。

+0

好的謝謝,只是想知道它是否可能。再一個簡單的問題。當我想根據ParentDiscussion找到所有討論的時候,我只是做了.Where(d => d.ParentId == SomeGuid),因爲我通過Data Annotations有一個外鍵。但有了這個解決方案,我必須做下面的.Where(d => d.ParentDiscussion.Id == SomeGuid),這不會導致額外的實際ParentDiscussion負載?或者EF將ParentDiscussion.Id翻譯爲「ParentId」屬性? –