Saya hanya dapat benar-benar mencapai ini dengan secara manual mengeluarkan pernyataan kunci ke tabel. Ini melakukan menyelesaikan kunci meja, jadi berhati-hatilah! Dalam kasus saya, ini berguna untuk membuat antrean yang tidak ingin saya sentuh beberapa proses sekaligus.
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();
}
Perbarui - Di Entity Framework 6, terutama dengan async
/ await
kode, Anda perlu menangani transaksi secara berbeda. Ini mogok bagi kami setelah beberapa konversi.
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();
}