0

I'm trying to do something simple with locking in sql server 2008 (or directly from asp.net mvc if possible) and not really sure how to handle it.

I have a table (call it users), and username has to be unique. I want to do something along the lines of

var myuser = db.users.FirstOrDefault(u => u.username == username); if(myuser == null) { myuser = new user(username); db.users.add(myuser); } return myuser; 

I need that to be atomic so that no one can try to insert user foo after someone else did. If this can be implemented from asp.net mvc, that would be perfect, but if not, I'll need to do it directly in a stored procedure. Is locking the right way to do this in the stored procedure? If so, do I need to lock the whole users table? I've also seen something with the merge keyword when looking online, but I'm not sure if that will help.

1 Answer 1

1

if you have high concurrency duplicate accounts could be created between the FirstOrDefault call, and the users.add call

if you add unique index on the username, sql will block the new row. then trap the error in code.

Sign up to request clarification or add additional context in comments.

1 Comment

i was doing that but I think in my situation it would make more sense to do it atomically and not rely on the unique index throwing an error.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.