2

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); How to fix my code to avoid this exception? thanks a lot!

4

1 回答 1

0

您已经实例化了一个对象上下文以最初加载对象,然后实例化了第二个以进行保存 - 您不能这样做,您需要为两者使用相同的对象上下文。

如果没有来自您的存储库的代码,很难看到您是如何做到这一点的,但是上面的注释应该可以帮助您修复它(可能是一个用于保存上下文的类级别变量,在类构造函数中实例化)。

于 2013-05-06T09:08:53.493 回答