【问题标题】:Exception thrown: The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects抛出异常:无法定义两个对象之间的关系,因为它们附加到不同的 ObjectContext 对象
【发布时间】:2013-05-06 09:05:26
【问题描述】:

我的代码:

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

在行时的异常提示:strategyIntent.StrategicDirectionLookups.Add(strategy.StrategicDirectionLookup); 如何修复我的代码以避免此异常?多谢!

【问题讨论】:

    标签: c# entity-framework


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2012-02-23
      • 2012-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多