简体   繁体   中英

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); 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM