实体框架附加由引用实体

时间:2016-09-14 12:04:21

标签: c# entity-framework

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

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

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

这是一个示例代码,其中包含用于解释问题的注释:

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

如何在没有例外的情况下附加两个实体?

1 个答案:

答案 0 :(得分:0)

问题在于附加物,请改用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();

我希望它有所帮助。

相关问题