sql >> Database >  >> RDS >> Sqlserver

Hoe kan ik een tabel vergrendelen bij lezen, met behulp van Entity Framework?

Ik kon dit alleen echt bereiken door handmatig een vergrendelingsverklaring aan een tafel te geven. Dit doet een complete tafelslot, dus wees er voorzichtig mee! In mijn geval was het handig om een ​​wachtrij te maken waarvan ik niet wilde dat meerdere processen tegelijk elkaar raakten.

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

Bijwerken - In Entity Framework 6, vooral met async / await code, moet u de transacties anders afhandelen. Dit crashte voor ons na enkele conversies.

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


  1. Servicegroepwijzigingen in R12.2

  2. Best practices:onderhouds- en verbeteringstaken voor Oracle Cloud

  3. Hoe u de huidige datum en tijd kunt krijgen (zonder tijdzone) in T-SQL

  4. Wijzig de startwaarde van Django AutoField