2013-07-26 48 views
2

在使用組合鍵多租戶應用 (例如SiteId, $(Table)Id) 的一切,我有以下兩個表:LINQ到SQL:複合FK只有一半爲空的

Owner (
    SiteId bigint NOT NULL, 
    OwnerId bigint NOT NULL, 
    ThingId bigint NULL 
) 

Thing (
    SiteId bigint NOT NULL, 
    ThingId bigint NOT NULL 
) 

Owner (SiteId, ThingId)的外鍵Thing (SiteId, ThingId)

如果我寫這樣的方法:

void RemoveThing(Owner owner) 
{ 
    owner.Thing = null; 
    db.SubmitChanges(); 
} 

我得到的異常

System.InvalidOperationException: An attempt was made to remove a relationship between a 
Thing and a Owner. However, one of the relationship's foreign keys (Owner.MultiId, 
Owner.ThingId) cannot be set to null. 
at System.Data.Linq.ChangeTracker.StandardChangeTracker.StandardTrackedObject.SynchDependentData() 
at System.Data.Linq.ChangeProcessor.ValidateAll(IEnumerable`1 list) 
at System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode) 
at System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode) 
at System.Data.Linq.DataContext.SubmitChanges() 
at proj.Program.RemoveThing() in C:\proj\Program.cs:line 115 

爲了解決這個問題,我的SiteId(也許ThingSiteId)第二副本添加到Owner表。但它只會等同於SiteId,所以我會花費數據庫大小和模式複雜度來解決我的ORM問題。

我該如何告訴LINQ to SQL它不需要擔心外鍵關係的一半,而只設置Owner.ThingId=NULL

+0

我不能直接回答這個問題,但我認爲這是值得考慮繞過linq2sql這一個操作和使用類似SqlCommand的東西。 –

+0

主人和事物表上的主要關鍵是什麼? – flup

+0

所有者上的PK是'SiteId,OwnerId',並且是'SiteId,ThingId' –

回答

3

設置ThingId = null而不是Thing = null。請勿重複使用DataContext,否則可能會出現「外鍵已設置」異常。


LINQ正在積極地防止這種情況變得更加簡單。在ChangeTracker.SynchDependentData(),每列進行檢查,看它是否是任何關聯的一部分,然後拋出一個異常,如果該列是

  1. 設置爲null

  2. 該協會有什麼非空列(!)

這是LINQ到SQL的錯誤,在我看來。