Is there any tools within Linq that would permit to lock a database or a set of tables explicitely ? I am working with a a few different databases and I am looking for something transparent. At my surprise, I couldn’t find much on the topic apart from topics dealing with how Linq deals with concurrency issues, which is out of my scope.
Alternatively, any other simple way for locking databases would be interesting to me (MsSql, Sybase in particular)
Locking databases is well outside of the scope of LINQ; the only locking aspects that are relevant would be the locking semantics a particular provider used to provide concurrency guarantees. You’ll need to go to something lower level if you want explicit locks beyond the ones that would be automatically applied by the transaction processing.
To execute arbitrary SQL commands through Entity Framework, you can use the
ExecuteStoreCommandmethod on the database context, which just takes a SQL string to execute. If for some reason you’re using the older LINQ2SQL provider, it has a similarExecuteCommandmethod for accomplishing the same goal.There really isn’t such a thing as a “database lock” (at least it database terminology), in the sense that the entire database can be quickly switched into an exclusive-access mode and back out. For Sybase (and MSSQL), someone with the proper rights can accomplish this by setting the “single user” option:
This is nowhere near as “simple” as just taking a lock: it means that only one person at a time will be allowed to connect to the database, so you need to make sure that you’re connected at the time you set the option on, and that no one else is connected (they will be kicked off without warning), and that you set the option back off when you’re done.
In MySql, as far as I’m aware, there’s no way to accomplish this short of changing everyone’s permissions on the target database.
Locking individual tables is a bit easier, as most database servers have SQL-like syntax for doing so. In MySql you use the
LOCK TABLEScommand, with aREADorWRITElock, though I strongly encourage you to read the linked page because MySql locking works (IMO) somewhat strangely. Sybase similarly has aLOCK TABLEcommand, in this case calledSHAREDandEXCLUSIVE.You are expected to lock tables within the context of a transaction, so you’ll probably want to wrap your code up in a
TransactionScopebefore you do any locking.