[英]Exception thrown: The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects
My Code: 我的代码:
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();
The exception prompt when in the line : strategicIntent.StrategicDirectionLookups.Add(strategy.StrategicDirectionLookup); 该行出现异常提示:strategyIntent.StrategicDirectionLookups.Add(strategy.StrategicDirectionLookup); How to fix my code to avoid this exception?
如何修复我的代码以避免此异常? thanks a lot!
非常感谢!
You have instantiated an object context to load the object initially and then instantiated a second one to do the saving - you can't do this, you need to use the same object context for both. 您已经实例化了一个对象上下文以首先加载该对象,然后实例化了另一个对象以进行保存-您不能这样做,您需要为两个对象都使用相同的对象上下文。
Without the code from your repository it is hard to see how you are doing this, but the above note should help you fix it (probably a class level variable to hold the context, instantiated in the class constructor). 没有存储库中的代码,很难看到如何执行此操作,但是上面的注释应该可以帮助您修复它(可能是一个类级变量来保存上下文,已在类构造函数中实例化)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.