此問題與我以前提出的問題類似。當我使用實體框架(EF)查詢數據時,我總是使用MergeOption.NoTracking
選項,因爲我最終獲取了EF生成的對象並將它們映射到查看模型,該模型在屬性上裝飾了可愛屬性以強制進行驗證等等。添加與實體框架的外鍵關係
我嘗試添加使用EF一個外鍵關係,但只要我做我得到以下異常:
The object being attached to the source object is not attached to the same ObjectContext as the source object
這裏是我的代碼:
public static void UpdateDownloadFileVersion(DownloadFile downloadFile, int[] selectedVersions) {
using (SupportEntity supportContext = new SupportEntity()) {
supportContext.DownloadFiles.Attach(downloadFile);
var productVersionIdsToAdd = (from v in selectedVersions
where (downloadFile.ProductVersions.Any(pv => pv.Id == v) == false)
select v).ToList();
foreach (var productVersionId in productVersionIdsToAdd) {
var productVersion = new ProductVersion() { Id = productVersionId };
downloadFile.ProductVersions.Attach(productVersion); //Exception happens here.
downloadFile.ProductVersions.Add(productVersion);
}
supportContext.SaveChanges();
}
}
嘗試這樣:var productVersion = new ProductVersion(){Id = productVersionId}; supportContext.ProductVersions.AttachTo(「ProductVersions」,productVersion); – 2012-02-28 16:05:46
@DmitrySavy - 我認爲你的意思是'supportContext.AttachTo(「ProductVersions」,productVersion)'。但是,是的,這是訣竅,但我真的不明白爲什麼。 'AttachTo'與'ProductVersions.Attach'有什麼不同?我也不喜歡這個解決方案,因爲現在代碼不是很強類型的,而且編譯時可能會忽略一個變化。 – 2012-02-28 16:18:15