2011-11-17 30 views
0

這似乎是最常見的關係,但由於某些原因,我無法獲得代碼優先的EF工作。當我運行代碼下面我得到以下錯誤:實體具有兩個屬性,這兩個屬性在一對多關係中引用相同的實體類型

* {「在介紹表‘錄音’可能會導致循環或多個級聯路徑外鍵約束‘Recording_RecordingLocation’指定ON DELETE NO ACTION或ON UPDATE NO ACTION。或修改其他FOREIGN KEY約束。\ r \ n無法創建約束。請參閱以前的錯誤。「} *

我有這麼研究和其他地方,但一直沒能想出解決辦法。我必須有輕微的中風,所以如果這是重複的,我很抱歉。我不認爲這是因爲我發現的所有其他參考問題都是針對多對多關係......多對一的。

我的情況是很簡單...

我有一個有兩個必需的屬性RecordingLocation和EditingLocation它們都是同一類型WorkLocation的實體(記錄)。每個錄音只有一個RecordingLocation和一個EditingLocation (非多對多)。我也有必要的導航屬性。

每個WorkLocation都是獨立的,並且與錄音本質上沒有關聯 - 它只是一個物理位置,在該位置錄製了一些錄音。所以當我刪除一個錄音時,我不想刪除相關的WorkLocations。

public class Recording 
{ 
    [Key] 
    public virtual int Id { get; set; } 

    //... other properties not shown here 

    public virtual int RecordingLocationId { get; set; } 
    public virtual WorkLocation RecordingLocation { get; set; } 

    public virtual int EditingLocationId { get; set; } 
    public virtual WorkLocation EditingLocation { get; set; } 
{ 


public class WorkLocation 
{ 
    [Key] 
    public virtual int Id { get; set; } 
    public virtual WorkLocationType Type { get; set; } 
    public virtual string Description { get; set; } 
    public virtual LogicalStatus Status { get; set; } 
} 

// I'll use this on the front-end to filter a selection list 
// but don't necessarily assume a Work Location is bound to only items of this type 
public enum WorkLocationType 
{ 
    RecordingLocation, 
    EditingLocation, 
    MasteringLocation 
} 

我錯過了什麼讓它工作?

+1

你真的是一個對一個,你的標題寫的,而不是一到多少?不能在同一個工作場所工作兩個或兩個以上的錄音嗎? – Slauma

+0

是的,它是一對多的。我在我的問題的某個地方說過「一對一」嗎?我在這個評論後重新閱讀,但沒有找到它,如果有的話,請編輯。 :-) – kingdango

+1

這個問題** TITLE ** :) – Slauma

回答

1

您的導航屬性RecordingLocationEditingLocation是必需的,因爲相應的外鍵屬性不可爲空。按照慣例,EF假定級聯刪除對於所需的一對多關係是活動的,如果您有多個此類關係引用同一個表,則會導致問題 - 因此是例外。

必須禁用級聯刪除(也是你的業務邏輯似乎都需要它),這是隻有在流利的API可能:

public class MyContext : DbContext 
{ 
    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     modelBuilder.Entity<Recording>() 
      .HasRequired(r => r.RecordingLocation) 
      .WithMany() 
      .HasForeignKey(f => f.RecordingLocationId) 
      .WillCascadeOnDelete(false); 

     modelBuilder.Entity<Recording>() 
      .HasRequired(r => r.EditingLocation) 
      .WithMany() 
      .HasForeignKey(f => f.EditingLocationId) 
      .WillCascadeOnDelete(false); 
    } 
} 
+0

立即嘗試此... – kingdango

+0

是的,這解決了這個問題。實際上,我曾嘗試過這樣做,但並不瞭解所需的流利語法......尤其是.WithMany()。我現在得到它,這工作。非常感謝您深思熟慮的答覆。 – kingdango

相關問題