【问题标题】:Updating the Record with EntityState.Modified but its inserting the new row rather than update使用 EntityState.Modified 更新记录,但它插入新行而不是更新
【发布时间】:2016-01-31 06:14:24
【问题描述】:

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

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

【问题讨论】:

  • 设置要修改的对象的主键(Id)
  • 主键已经存在

标签: c# entity-framework-6


【解决方案1】:

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

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

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

如果这个产品有其他表的外键,你也应该检查这个问题和答案:

Difference between updating an entity by using a foreign key and using the navigation properties In Entity Framework

【讨论】:

    猜你喜欢
    • 2020-07-19
    • 2014-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-16
    • 1970-01-01
    相关资源
    最近更新 更多