sql >> Base de Datos >  >> RDS >> Sqlserver

¿Cómo puedo bloquear una tabla en lectura, usando Entity Framework?

Realmente solo pude lograr esto emitiendo manualmente una declaración de bloqueo a una tabla. Esto hace un completo Bloqueo de mesa, ¡así que ten cuidado con eso! En mi caso, fue útil para crear una cola que no quería que varios procesos tocaran a la vez.

using (Entities entities = new Entities())
using (TransactionScope scope = new TransactionScope())
{
    //Lock the table during this transaction
    entities.Database.ExecuteSqlCommand("SELECT TOP 1 KeyColumn FROM MyTable WITH (TABLOCKX, HOLDLOCK)");

    //Do your work with the locked table here...

    //Complete the scope here to commit, otherwise it will rollback
    //The table lock will be released after we exit the TransactionScope block
    scope.Complete();
}

Actualizar - En Entity Framework 6, especialmente con async / await código, necesita manejar las transacciones de manera diferente. Esto se bloqueó para nosotros después de algunas conversiones.

using (Entities entities = new Entities())
using (DbContextTransaction scope = entities.Database.BeginTransaction())
{
    //Lock the table during this transaction
    entities.Database.ExecuteSqlCommand("SELECT TOP 1 KeyColumn FROM MyTable WITH (TABLOCKX, HOLDLOCK)");

    //Do your work with the locked table here...

    //Complete the scope here to commit, otherwise it will rollback
    //The table lock will be released after we exit the TransactionScope block
    scope.Commit();
}