SQL >> Base de Datos >  >> RDS >> Sqlserver

¿Cómo bloquear una tabla para lectura con Entity Framework?

En realidad solo conseguí hacerlo emitiendo manualmente una instrucción de bloqueo sobre la tabla. Esto aplica un bloqueo total de la tabla, ¡así que ten cuidado con él! En mi caso resultó ú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(); } 

Actualización: en Entity Framework 6, sobre todo con código async / await, necesitas manejar las transacciones de otra manera. A nosotros nos empezó a fallar tras 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(); }