entity-framework - EF Core 在保存附加实体时抛出 DbUpdateConcurrencyException
问题描述
我想更新实体的某些列而不将整个实体加载到内存中。基于SO post我正在尝试实现我的逻辑。建议的答案是使用 EF 4.1,但我假设同样适用于 EF Core。(我正在使用 EF Core)
表中有更多列,但为简洁起见,此处仅显示少数列
[LearningDocuments]
LearningDocumentId (int),
LearningRequestID (int) (foriegnkey),
IsDone (bit),
CreatedDateTime (datetime),
ModifiedDateTime (dateTime)
VersionStamp (timestamp)
更新某些列的代码
var dbContext = GetDBContext();
var documents = await dbContext.LearningDocuments
.Where(x => x.LearningRequestID == 1234)
.Select(x => new LearningDocument()
{
LearningDocumentId = x.LearningDocumentId ,
IsDone = x.IsDone,
ModifiedDateTime = x.ModifiedDateTime
})
.ToListAsync()
.ConfigureAwait(false);
documents.ForEach(d =>
{
d.IsDone = true;
d.ModifiedDateTime = DateTime.UtcNow;
dbContext.LearningDocuments.Attach(d);
dbContext.Entry(d).Property(x => x.IsDone).IsModified = true;
dbContext.Entry(d).Property(x => x.ModifiedDateTime).IsModified = true;
});
await dbContext.SaveChangesAsync().ConfigureAwait(false);
但是保存更改会引发异常:
Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException:数据库操作预计会影响 1 行,但实际上影响了 0 行。自加载实体以来,数据可能已被修改或删除
LearningDocument
是一个实体。我将结果投影到LearningDocument
仅选择所需列的新实例中,可以吗?
解决方案
推荐阅读
- python - 使用 For 循环打开文件 (Python 3)
- android - Android 5+ 光栅和矢量图像冲突
- asp.net-mvc - 使用模型中的项目的完整日历调度程序资源
- hyperledger-composer - 在 IBM Container Service 的免费计划上创建基本 IBM Blockchain 网络时出错
- sql - 对 SQL 表中的多个列执行搜索操作的有效方法是什么
- mysql - 您如何在数据类型中至少有 1 个东西?
- javascript - G-SVG 没有在其中显示我的图像 - react-native
- swift4 - 使用 audiokit 接收 Sysex 消息
- ruby-on-rails - 在 Rails 中查看用户通过 Facebook 注册的天气
- python - 从 PDF 自动打印页面