我的代码:
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);如何修复我的代码以避免此异常?多谢!
您已经实例化了一个对象上下文来最初加载对象,然后实例化了第二个对象上下文来进行保存 - 您不能这样做,您需要为两者使用相同的对象上下文。
如果没有您存储库中的代码,很难看出您是如何做到这一点的,但上面的说明应该可以帮助您修复它(可能是一个类级变量来保存上下文,在类构造函数中实例化)。
我是一名优秀的程序员,十分优秀!