Reputation: 2049
I want to do this query to bypass concurrency conflicts on Balance
column.
Update SomeTable
set Balance = Balance + 500
where Id = someId
I know one solution is to use DbContext.Database.ExecuteSqlCommand()
and another solution is to use Optimistic Concurrency Check
.
Is there any way to do the query using EF Core (nor ExecuteSqlCommand
neither optimistic concurrency check
)?
Upvotes: 1
Views: 1092
Reputation: 139
I think EFCore.BulkExtensions library should be able to solve your problem. and other more powerful library Z.EntityFramework.Plus.EFCore.
EFCore.BulkExtensions
:
// Delete
context.Items.Where(a => a.ItemId > 500).BatchDelete();
context.Items.Where(a => a.ItemId > 500).BatchDeleteAsync();
// Update (using Expression arg.) supports Increment/Decrement
context.Items.Where(a => a.ItemId <= 500).BatchUpdate(a => new Item { Quantity = a.Quantity + 100 });
// can be as value '+100' or as variable '+incrementStep' (int incrementStep = 100;)
// Update (via simple object)
context.Items.Where(a => a.ItemId <= 500).BatchUpdate(new Item { Description = "Updated" });
context.Items.Where(a => a.ItemId <= 500).BatchUpdateAsync(new Item { Description = "Updated" });
// Update (via simple object) - requires additional Argument for setting to Property default value
var updateColumns = new List<string> { nameof(Item.Quantity) }; // Update 'Quantity' to default value('0'-zero)
var q = context.Items.Where(a => a.ItemId <= 500);
int affected = q.BatchUpdate(new Item { Description = "Updated" }, updateColumns);//result assigned to variable
reference: EF Core Tools & Extensions
Upvotes: 2
Reputation: 26432
You are not really bypassing concurrency conflicts by executing the query.
EF Core implements optimistic concurrency control, meaning that it will let multiple processes or users make changes independently without the overhead of synchronization or locking.
This means that ef core objects will update in memory without locking until you call save changes.
So, whether or not you execute the query, it will not stop anyone attaching the object and update it at the same time.
By the way, optimistic concurrency is the default ef setting.
Upvotes: 1