updaing \\与EF节省违反了DB uniquness限制 [英] updaing\saving with EF violates a DB uniquness restriction

查看:418
本文介绍了updaing \\与EF节省违反了DB uniquness限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用EF更新实体。

下面是我的code:

    public MamConfiguration_V1 Save(MamConfiguration_V1 item)
    {
            item.ThrowIfNull("item");

            mMaMDBEntities.MamConfiguration_V1.AddObject(item);

            mMaMDBEntities.ObjectStateManager.ChangeObjectState(item, System.Data.EntityState.Modified);

            mMaMDBEntities.SaveChanges();

            return item;
    }

然而以这种方式,我得到一个数据库中的PK违反erorr。

However in this way I get a PK violation erorr in the DB.

I $用这种方式(创建一个新的EF实体)和其标记为

I prefer to use this way (creating a new EF entity) and marking it as

修改,哪能不破uniquness限制?

modified, how can I not break the uniquness restriction?

推荐答案

如果您正在使用这个方法来更新现有的项目,然后您会收到由于异常

If you are using this method to update the existing item, then you receive the exception because of the

  mMaMDBEntities.MamConfiguration_V1.AddObject(item);

行。它看起来像这样code你正试图把该项目到表中的第二次。如果我猜得不错,你用这种方法来更新现有的项目,你只应删除此行 - EF会根据您将对象的字段所做的更改自动更新数据库。

line. It looks like with this code you are trying to put the item into your table for the second time. If I guessed right and you use this method to update your existing items, you just should remove this line - EF will automatically update the DB according to the changes you made to your object's fields.

这篇关于updaing \\与EF节省违反了DB uniquness限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆