I wanted to update certain columns of the entity without loading entire entity into memory. Based on SO post i am trying to implement my logic. The suggested answer is using EF 4.1 but i am assuming same will work in EF Core. ( i am using EF Core)
There are more columns in the table but for brevity only few are displayed here
[LearningDocuments]
LearningDocumentId (int),
LearningRequestID (int) (foriegnkey),
IsDone (bit),
CreatedDateTime (datetime),
ModifiedDateTime (dateTime)
VersionStamp (timestamp)
Code to update certain columns
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);
However save changes is throwing exception:
Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException : Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded
LearningDocument
is an entity. I am projecting the result into new LearningDocument
instances selecting only required columns, is that okay?