1

我想更新实体的某些列而不将整个实体加载到内存中。基于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仅选择所需列的新实例中,可以吗?

4

0 回答 0