![](/img/trans.png)
[英]The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects Entity Framework
[英]Exception thrown: The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects
我的代碼:
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();
該行出現異常提示:strategyIntent.StrategicDirectionLookups.Add(strategy.StrategicDirectionLookup); 如何修復我的代碼以避免此異常? 非常感謝!
您已經實例化了一個對象上下文以首先加載該對象,然后實例化了另一個對象以進行保存-您不能這樣做,您需要為兩個對象都使用相同的對象上下文。
沒有存儲庫中的代碼,很難看到如何執行此操作,但是上面的注釋應該可以幫助您修復它(可能是一個類級變量來保存上下文,已在類構造函數中實例化)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.