gpt4 book ai didi

c# - 如何使用 Entity Framework 6 更新记录?

转载 作者:IT王子 更新时间:2023-10-29 03:29:22 25 4
gpt4 key购买 nike

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

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

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

{System.Data.Entity.Infrastructure.DbUpdateConcurrencyException: Storeupdate, insert, or delete statement affected an unexpected number ofrows (0). Entities may have been modified or deleted since entitieswere loaded. Refresh ObjectStateManager entries

最佳答案

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

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

关于c# - 如何使用 Entity Framework 6 更新记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25894587/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com