2012-02-28 85 views
1

此問題與我以前提出的問題類似。當我使用實體框架(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(); 
     } 
    } 
+0

嘗試這樣:var productVersion = new ProductVersion(){Id = productVersionId}; supportContext.ProductVersions.AttachTo(「ProductVersions」,productVersion); – 2012-02-28 16:05:46

+0

@DmitrySavy - 我認爲你的意思是'supportContext.AttachTo(「ProductVersions」,productVersion)'。但是,是的,這是訣竅,但我真的不明白爲什麼。 'AttachTo'與'ProductVersions.Attach'有什麼不同?我也不喜歡這個解決方案,因爲現在代碼不是很強類型的,而且編譯時可能會忽略一個變化。 – 2012-02-28 16:18:15

回答

2

這是存根實體變得非常非常有用的地方...

var productVersion = new ProductVersion() { Id = productVersionId }; 
supportContext.AttachTo("ProductVersions", productVersion); 

這裏是一個很好article

在上述情況下,當附着productVersion被分配給product versions「實體指productversion實體被連接到上下文,與EntityState=Added。整個圖形將處於或不在上下文中。

+0

確切的說,這是待辦事項的方式,不要嘗試其他的東西,它會在某個時候破壞你的脖子! – ntziolis 2012-02-28 16:25:39

+0

@ntziolis - 我已經在使用存根實體(請參閱我的發佈代碼),但它不起作用(我得到了異常)。 – 2012-02-28 16:28:58

+0

@Dmitry Savy - 我正在使用存根實體,但我仍然得到一個異常拋出。爲什麼我需要用字符串調用'AttachTo'而不是所謂的'ProductVersions.Attach'? – 2012-02-28 16:30:01