c# – 连接类型“X”的实体失败,因为另一个相同类型的实体

前端之家收集整理的这篇文章主要介绍了c# – 连接类型“X”的实体失败,因为另一个相同类型的实体前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在代码中偶然发现了一个奇怪的错误.这是以前工作,但现在有时工作.

我正在使用EF6编辑一个关系的实体.
不要编辑我附加的关系(参见示例代码).

public void EditA(A ThisIsA,B ThisIsB)
    {
        using (var Context = new LDZ_DEVEntities())
        {
            Context.As.Attach(ThisIsA);

            var b = Context.Bs.FirstOrDefault(x => x.BId == ThisIsB.BId);
            //var b = Context.Bs.Find(ThisIsB.BId);

            if (b != null)
                Context.Bs.Attach(b);
            else
                b = ThisIsB;

            if (b.C != null)
                Context.Cs.Attach(b.C);

            ThisIsA.Bs.Add(b);

            Context.SaveChanges();

        }
    }

我已经编辑了名称以保持简单.

以下行

Context.Cs.Attach(b.C);

抛出这个错误

Attaching an entity of type ‘C’ Failed because another entity of the same type already has the same primary key value. This can happen when using the ‘Attach’ method or setting the state of an entity to ‘Unchanged’ or ‘Modified’ if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the ‘Add’ method or the ‘Added’ entity state to track the graph and then set the state of non-new entities to ‘Unchanged’ or ‘Modified’ as appropriate.

引入了这一行,因为所有C实体都是静态实体.我从来不想要创建一个C.如果我删除这行,每次当我添加一个B到A;创建了一个C.哪个是不可取的.

额外信息:
A有一个B的列表
B有一个C

这个EditA()方法正在我的软件中的多个地方被调用.此错误仅在循环(导入)中调用方法显示.在第一个记录工作时没有问题.但是,在第一个记录之后我收到错误.

我已经阅读了这些问题和答案,但他们并不适合我:

> ASP.NET MVC – Attaching an entity of type ‘MODELNAME’ failed because another entity of the same type already has the same primary key value
> Attaching an entity of type failed because another entity of the same type already has the same primary key value

解决方法

我修好了它.

他在法比奥·卢兹(Fabio Luz)的回答中说:

//if A has been loaded from context
//dont attach it
//if it has been created outside of the context
//Context.Entry(ThisIsA).State = EntityState.Modified;

这让我想到了,所以我编辑了我的代码

public void EditA(A ThisIsA,B ThisIsB)
{
    using (var Context = new LDZ_DEVEntities())
    {
        var a = Context.As.Find(ThisIsA.AId);

        //var b = Context.Bs.FirstOrDefault(x => x.BId == ThisIsB.BId);
        var b = Context.Bs.Find(ThisIsB.BId);

        if (b != null)
            Context.Bs.Attach(b);
        else
            b = ThisIsB;

        if (b.C != null)
            Context.Cs.Attach(b.C);

        a.Bs.Add(b);

        Context.SaveChanges();

    }
}

变更摘要

>更改首个失败查找
>从上下文获取A

起初我删除了C的附件,结果创建了一个新的实体.
所以我扭转了这个变化.

特别感谢Fabio Luz.没有你的帮助,我无法做到这一点!

原文链接:https://www.f2er.com/csharp/95072.html

猜你在找的C#相关文章