2013-05-06 46 views
2

我的代碼:拋出異常:因爲它們連接到不同的ObjectContext不能限定的兩個對象之間的關係的對象

StrategyRepository strategyRepository = new StrategyRepository(); 
StrategyLookup strategy = strategyRepository.GetStrategy(int.Parse(hidSelectedStrategyID.Value.ToString())); 

     //StrategicDirectionRepository strategicDirectionRepository = new StrategicDirectionRepository(); 
     StrategicDirectionLookup strategicDirection = strategyRepository.GetStrategicDirection(cb_StrategyDirectionsEdit.Value.ToString()); 
     if (strategicDirection == null) { 
      strategicDirection = new StrategicDirectionLookup() { 
       Caption = cb_StrategyDirectionsEdit.Value.ToString(), 
       SequenceNo = 100 
      }; 
      //strategyRepository.AddStrategicDirection(strategicDirection); 
     } 

     //StrategicIntentRepository strategicIntentRepository = new StrategicIntentRepository(); 
     StrategicIntentLookup strategicIntent = strategyRepository.GetStrategicIntent(cb_StrategyIntentsEdit.Value.ToString()); 
     if (strategicIntent == null) { 
      strategicIntent = new StrategicIntentLookup() { 
       Caption = cb_StrategyIntentsEdit.Value.ToString(), 
       SequenceNo = 100 
      }; 
      //strategyRepository.AddStrategicIntent(strategicIntent); 
     } 

     strategy.Caption = txtStrategyEdit.Value.ToString(); 
     if (!strategicDirection.StrategyLookups.Select(o=>o.SID).Contains(strategy.SID)) 
     { 
      strategicDirection.StrategyLookups.Add(strategy); 
     } 

     if (!strategicIntent.StrategicDirectionLookups.Select(o=>o.SDID).Contains(strategy.StrategicDirectionLookup.SDID)) 
     { 

      strategicIntent.StrategicDirectionLookups.Add(strategy.StrategicDirectionLookup); 
     } 
     strategyRepository.SaveChanges(); 

的異常提示當行:strategicIntent.StrategicDirectionLookups.Add(strategy.StrategicDirectionLookup ); 如何修復我的代碼以避免此異常?非常感謝!

回答

0

你已經實例化了一個對象上下文來初始化對象,然後實例化第二個對象進行保存 - 你不能這樣做,你需要爲兩者都使用相同的對象上下文。

沒有來自你的倉庫的代碼,你很難看到你是如何做到這一點的,但上面的註釋應該可以幫助你修復它(可能是一個用於保存上下文的類級變量,在類的構造函數中實例化)。

+0

謝謝!我現在明白了! – user2354024 2013-05-06 10:10:14

相關問題