如何使用 Entity Framework 6 更新记录? [英] How to update record using Entity Framework 6?

查看:24
本文介绍了如何使用 Entity Framework 6 更新记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 EF6 更新记录.首先找到记录,如果存在,更新.这是我的代码:

I am trying to update a record using EF6. First finding the record, if it exists, update. Here is my code:

var book = new Model.Book
{
    BookNumber =  _book.BookNumber,
    BookName = _book.BookName,
    BookTitle = _book.BookTitle,
};
using (var db = new MyContextDB())
{
    var result = db.Books.SingleOrDefault(b => b.BookNumber == bookNumber);
    if (result != null)
    {
        try
        {
            db.Books.Attach(book);
            db.Entry(book).State = EntityState.Modified;
            db.SaveChanges();
        }
        catch (Exception ex)
        {
            throw;
        }
    }
}

每次我尝试使用上述代码更新记录时,都会收到此错误:

Every time I try to update the record using the above code, I am getting this error:

{System.Data.Entity.Infrastructure.DbUpdateConcurrencyException:存储更新、插入或删除语句影响了意外数量的行 (0).实体可能已被修改或删除,因为实体被加载.刷新 ObjectStateManager 条目

{System.Data.Entity.Infrastructure.DbUpdateConcurrencyException: Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries

推荐答案

您正在尝试更新记录(对我来说,这意味着更改现有记录上的值并将其保存回来").因此,您需要检索对象、进行更改并保存它.

You're trying to update the record (which to me means "change a value on an existing record and save it back"). So you need to retrieve the object, make a change, and save it.

using (var db = new MyContextDB())
{
    var result = db.Books.SingleOrDefault(b => b.BookNumber == bookNumber);
    if (result != null)
    {
        result.SomeValue = "Some new value";
        db.SaveChanges();
    }
}

这篇关于如何使用 Entity Framework 6 更新记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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