How to update record using Entity Framework 6?(如何使用 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 更新记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 Entity Framework 6 更新记录?


- MoreLinq maxBy vs LINQ max + where 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01