实体框架附加由引用实体的自动递归附加引起的异常

本文关键字:实体 异常 递归 引用 框架 | 更新日期: 2023-09-27 18:07:08

我有两个分离的实体,它们已经急切地加载了多个其他实体。(1到n的关系)

引用分离实体的急切加载实体(存储在iccollection导航属性中)可以同时存在于两个分离实体中。

当我想要附加两个分离的实体时,我得到一个异常,因为急切加载的实体已经附加了。

这是一个示例代码,带有注释来解释问题:

public ProvokeAttachException()
{
    //s1 and s2 share some of their samples
    sample_set s1 = GetSampleSet(1);
    sample_set s2 = GetSampleSet(2);
    //Do some stuff
    //Attaching the sample_sets again
    using(StationContext context = new StationContext())
    {
        // Fine
        context.sample_set.Attach(s1);
        //Throws Exception because some of the included samples in sample_set
        //have been attached automatically with s1
        context.sample_set.Attach(s2); 
    }
}
public sample_set GetSampleSet(int setId)
{
    //Eager Loading all samples that reference sample_set (1 to n relation)
    using (StationContext context = new StationContext())
    {
        return context.sample_set.Include("sample").FirstOrDefault(s => s.id = setId);
    }
}

如何在没有异常的情况下连接两个实体?

实体框架附加由引用实体的自动递归附加引起的异常

问题是附加的东西,用Add代替。

当您执行context.sample_set.Attach(s1);时,它真正做的是在新上下文中创建所有相关对象的实例,然后将它们添加到sample_set中,这就是它工作的原因。

当您尝试创建context.sample_set.Attach(s2);时,它试图再次创建所有共享的samples,这就是为什么它抛出异常。

所以我的建议是:

context.sample_set.Add(s1);
context.sample_set.Add(s2);
context.SaveChanges();