As far as I\'ve understood it, there is no option in EF (and EF Core) to explicitly lock resources which I\'m querying, but I\'ll need this functionality quite often and don
According to this issue there is no easy way to implement locks hints and other database oriented calls in ef core
I implemented UPDLOCK with MsSQL and ef core in my project this way:
public static class DbContextExtensions
{
public static string GetUpdLockSqlForEntity(this DbContext dbContext, int entityPk, bool pkContainsTableName = true) where T : class
{
var mapping = dbContext.Model.FindEntityType(typeof(T)).Relational();
var tableName = mapping.TableName;
var entityPkString = entityPk.ToString();
string idPrefix = pkContainsTableName ? tableName.Substring(0, tableName.Length - 1) : string.Empty;
return $"Select 1 from {tableName} with (UPDLOCK) where {idPrefix}Id = {entityPkString}";
}
}
We are using this method in database transaction as raw sql call(lock will be released after commit or rollback):
using (var dbTran = await DataContext.Database.BeginTransactionAsync(IsolationLevel.ReadCommitted))
{
try
{
await DataContext.Database.ExecuteSqlCommandAsync(DataContext.GetUpdLockSqlForEntity(entityId));
dbTran.Commit();
}
catch (Exception e)
{
dbTran.Rollback();
throw;
}
}