gpt4 book ai didi

c# - 异常抛出 : The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects

转载 作者:太空宇宙 更新时间:2023-11-03 16:13:59 25 4
gpt4 key购买 nike

我的代码:

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);如何修复我的代码以避免此异常?多谢!

最佳答案

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

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

关于c# - 异常抛出 : The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16395365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com