Is there a known extension for Entity Framework Core that can do this bulk update as in this SqlRaw example?
dbc.Database.ExecuteSqlRawAsync(
"UPDATE [Assembly] SET OnHold = @OnHold, UpdatedWith = @UpdatedWith, UpdatedAt = @UpdatedAt, UpdatedById = @UpdatedById FROM [Assembly] INNER JOIN Station ON [Assembly].StationID = Station.ID INNER JOIN Project ON Station.ProjectID = Project.ID WHERE Project.ID = @ProjectID",
onHold, updatedWith, updatedAt, updatedById, projectID)
I would suggest linq2db.EntityFrameworkCore<\/a> (disclaimer: I'm one of the creators)
var updateQuery =
from a in ctx.Assembly
join s in ctx.Station on a.SationId equals s.ID
join p in ctx.Project on s.ProjectId equals p.ID
where p.ID == projectId
select a;
var recordsAffected = await updateQuery
.Set(a => a.OnHold, onHold)
.Set(a => a.UpdatedWith, updatedWith)
.Set(a => a.UpdatedAt, a => Sql.CurrentTimeStamp)
.Set(a => a.UpdatedById, updatedById)
.UpdateAsync();
The IQueryable.ToQueryString
method introduced in Entity Framework Core 5.0 may help reduce/simplify the raw SQL used in your code. This method will generate SQL that can be included in a raw SQL query to perform a bulk update of records identified by that query.
For example:
var query =
from a in dbc.Assembly
join s in dbc.Station on a.StaionId equals s.Id
join p in dbc.Project on s.ProjectId equals p.Id
where p.Id == projectId
select a.Id;
var sql = $@"
UPDATE Assembly
SET OnHold = {{0}}, UpdatedWith = {{1}}, UpdatedAt = {{2}}, UpdatedById = {{3}}
WHERE Id IN ({query.ToQueryString()})
";
dbc.Database.ExecuteSqlRawAsync(sql, onHold, updatedWith, updatedAt, updatedById);
The major drawback of this approach is the use of raw SQL. However I don't know of any reasonable way to avoid that with current Entity Framework Core capabilities - you're stuck with this caveat, or the caveat of introducing a dependency on another library such as linq2db.EntityFrameworkCore as mentioned in another answer here.
If (when) the following issue is addressed in the future then we are likely to have a better answer to this question: Bulk (ie set-based) CUD operations (without loading data into memory) #795
Just a little patience there will be the built-in BulkUpdate()
as well as BulkDelete
methods in EFCore which will be delivered in EFCore 7.0
context.Customers.Where(...).BulkDelete();
context.Customers.Where(...).BulkUpdate(c => new Customer { Age = c.Age + 1 });
context.Customers.Where(...).BulkUpdate(c => new { Age = c.Age + 1 });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.