How to implement Select For Update in EF Core

前端 未结 2 1030
鱼传尺愫
鱼传尺愫 2021-01-13 03:03

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

2条回答
  •  迷失自我
    2021-01-13 03:42

    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;
        }
    }
    

提交回复
热议问题