我的代码:
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)
您已实例化一个对象上下文以最初加载该对象,然后实例化第二个以进行保存 - 您无法执行此操作,您需要为两者使用相同的对象上下文。
如果没有来自存储库的代码,很难看到你是如何做到的,但上面的注释应该可以帮助你修复它(可能是一个类级变量来保存上下文,在类构造函数中实例化)。