![](/img/trans.png)
[英]How to determine if Navigation Property in the Entity Framework is set without loading the related records
[英]How to set up Navigation Properties to enforce deleting related records
我正在使用帶有實體框架6.1.x的MVC 4和VS2010。 我正在使用Code First相當簡單的數據庫,但是其中有一個稍微復雜的部分。 首先,兩個表Person
和Recording
關系為1。
public class Person {
public int PersonID { get; set; }
public int GenderID { get; set; }
// Navigation property
public virtual List<Recording> Recordings { get; set; }
}
public class Recording {
public int RecordingID { get; set; }
// ...
public int PersonID { get; set; }
// Navigation properties
public virtual Person Person { get; set; }
public virtual List<Junction> Junctions { get; set; }
}
默認情況下,當我刪除Person
,實體框架會刪除與Person
相關的所有記錄。 這就是我的期望。 但是,從記錄Recording
表也被放置在不同的組表。 假設我有一個名為Applicant
, Application
和Junction
。 通過刪除Person
或Recording
刪除任何記錄時,我也希望刪除Junction
中與Recording
中的Recording
相關的所有記錄。 在我的項目中,如果與特定應用程序相關的記錄數量為零,那將是沒有意義的。
有一個組合的Primary Key
,即Junction
ApplicantID
, ApplicationID
和RecordID
組成了復雜的Key。
是否可以通過Entity Framework強制約束,或者我不得不提供自己的自定義功能?
如何在相應的表中設置導航屬性: Recording
和Junction
以便刪除相關的記錄?
public class Applicant
{
public int ApplicantID { get; set; }
// Navigation property
public virtual List<Junction> Junctions { get; set; }
}
public class Application {
public int ApplicationID { get; set; }
// Navigation property
public virtual List<Junction> Junctions { get; set; }
}
public class Junction
{
public int ApplicationID { get; set; }
public int ApplicantID { get; set; }
public int RecordingID { get; set; }
public virtual Application Application { get; set; }
public virtual Applicant Applicant { get; set; }
public virtual Recording Recording { get; set; }
}
謝謝你的幫助。
@克里斯。 據我了解,如果外鍵不可為空,則如果刪除主表中具有相應PrimaryID的記錄,則會刪除輔助表中的記錄。 另一方面,如果外鍵可為空,則輔助表中的記錄將變為null
但不會刪除。
我創建了這個項目和兩個表,並填充了數據庫。 在Student
類中,如果我讓DepartmentID
不可為空,
public int? DepartmentID { get; set; }
刪除具有主要DepartmentID
記錄時,將刪除記錄。 這就是我的期望,但是如果我將DepartmentID
設為可為空
public int? DepartmentID { get; set; }
然后我有這個錯誤:
DELETE語句與REFERENCE約束“ FK_dbo.Student_dbo.Department_DepartmentID”沖突。 數據庫“ TestDB”的表“ dbo.Student”的列“ DepartmentID”中發生了沖突。
該語句已終止。
在測試項目中,我制作了兩個表,它們之間的關系為1。
public partial class Student : IDisposable
{
public int StudentID { get; set; }
public int DepartmentID { get; set; }
public virtual Department Department { get; set; }
}
和
public partial class Student : IDisposable { public int StudentID { get; set; } public int DepartmentID { get; set; } public virtual Department Department { get; set; } }
這是我應該期待的嗎?
刪除級聯並不旨在僅憑即興刪除項目。 它的存在是不必要的。 在上面的示例中, Recording
對Person
擁有一個不可為空的外鍵。 如果刪除了該Person
,則必須將外鍵設置為null(這不會發生),或者必須刪除所有相關的Recording
以保持引用完整性。
在帶有Junction
的第二個示例中, Record
包含一個不可為空的外鍵。 因此,如果您刪除一個Person
所有與這些記錄相關的Record
和Junction
都將被刪除。 但是,如果刪除一個Junction
,則不會采取進一步的措施。 內在沒有任何依賴於Junction
因此刪除它的過程不會引起注意。 一旦引用,任何Record
仍然有效。 請記住,這都是關於維護參照完整性的。 只要完整性是完整的,就不會刪除任何內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.