使用EntityState.Modified更新记录,但插入新行而不是更新 [英] Updating the Record with EntityState.Modified but its inserting the new row rather than update

查看:351
本文介绍了使用EntityState.Modified更新记录,但插入新行而不是更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用EF6,在这里我试图通过使用EntityState.Modified状态来更新数据库中的现有记录,但是它在表中插入新行而不是对其进行更新.我正在使用以下代码,请让我知道我要去哪里错了.

I am using EF6 and in this i am trying to update the existing record in the database by using the EntityState.Modified state but its inserting the new row in the table rather tha updating it.I am using following code please let me know where i am going wrong.

public Product UpdateProduct(ProductVM objProduct)
{
    Product obj = new Product();
    obj = JsonConvert.DeserializeObject<Product>(JsonConvert.SerializeObject(objProduct));
    DbContext.Entry(obj).State = EntityState.Modified;
    DbContext.SaveChanges();
    return obj;
}

推荐答案

之所以发生这种情况,是因为实体框架不知道"您的这个实体.您只传递了一种视图模型,即使您知道它具有PK或FK,EF也无法知道该怎么做,因此它会创建一个新模型.看到您创建了new Product()吗?此行创建一个新产品,由于它是新产品,EF会将其状态视为已添加".

This is happening because Entity Framework is "unaware" of this entity of yours. You are passing just a view model and even though you know it has a PK or FK, there's no way EF knows what to do, so it creates a new one. See that you create a new Product()? This line, creates a new Product and since it is new, EF will treat its state as Added.

相反,您需要首先从数据库获取对象,然后更改字段.像这样:

Instead, you need to first get your object from DB then change the fields. Something like this:

public Product UpdateProduct(ProductVM objProduct)
{
    obj = JsonConvert.DeserializeObject<Product>(JsonConvert.SerializeObject(objProduct));

    //Get the product from DB to update
    var product = DbContext.SingleOrDefult(x => x.Id == objProduct.Id);

    //update fields...
    product.SomeField = obj.SomeField;

    //Save changes
    DbContext.Entry(product).State = EntityState.Modified;
    DbContext.SaveChanges();

    return product;
}

如果该产品具有指向其他表的外键,则您也应该检查该问题并回答:

If this Product has foreign keys to other tables you should check this question and answer too:

查看全文

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