charly's
charly's

Reputation: 299

Lock Db Asp.Net via ApplicationContext

I got a db where I need to write entries to a table. I need to make sure that my table will contain only 20 rows at any given time (I'm making it simple). Of course, since I am in a web app, I have several users at the same time.

This is what I plan to do :

I use an aspx page with a button "AddRecord", when I click on it, I do this :

public void click(event e...)
{
    Object lockInstance = ApplicationContext["lockObject"];
    if (lockInstance  == null)
     {
     // Create Object and store it in app context.

     }

    lock(lockInstance)
    {
          // Run Query select count bla bla
          // if count < 20 then insert...
    }

}

No triggers, or stored proc (no I'm not biased, the person I'm working for is :) )

Is there a better way than to rely on the Application Context ?

Thank you

Upvotes: 0

Views: 71

Answers (1)

Ilkka
Ilkka

Reputation: 306

Your solution wouldn't work on a web garden or load balanced web farm scenario. I suggest you use proper DB locks.

You can, for example. begin a transaction, execute a select statement using TABLOCKX (which locks the table exclusively), add some rows, if there are less than 20, and finally commit the transaction.

See locking hints.

Upvotes: 1

Related Questions