3

I'm currently creating a method on my data access class that is going to insert an entity object to the database and I was expecting to get the latest inserted ID afterwards... and I've already done that but then I was wondering what would happend if the method somehow gets invoked twice at the same time, would it return the wrong ID?

So as a work around to that I decided to Lock the table on my datacontext:

lock(dataContext.Persons)
{
    InsertOnSubmit(person);
    dataContext.SubmitChanges();
}

but I do feel like this is inappropriate... I mean, the table isnt big and it wont take long to the datacontext to submit changes... So my question is, what kind of trouble would I run into by locking it like that?

PS: Let me know if my question was not clear enough and I'll edit it!

2 Answers 2

1

There is no need to lock your table.

LINQ-to-SQL will automatically populate your ID field with the identity from the database upon your call to .SubmitChanges() when you insert your person.

The caveat is that both your database and L2S entity must define your ID field as an identity. On your Person entity, you should have that field defined as the primary key, IsDbGenerated=true, UpdateCheck=never, and have the correct database type.

Once you submit, you should be able to simply retrieve the ID from your Person entity:

dataContext.Persons.InsertOnSubmit(person);
dataContext.SubmitChanges();
var id = person.ID; // now has the database generated identity.
4
  • Ok thank you.. but do you know what could possibly go wrong if I had this lock?
    – BSarkis
    Oct 26, 2011 at 17:12
  • @BSarkis: Not sure what you mean by go wrong. You aren't preventing anyone from touching that table outside of this lock, you're only protecting this single block of code from concurrency.
    – Marc
    Oct 26, 2011 at 20:16
  • I see, that is the kind of answer I was looking for, thank you once again.
    – BSarkis
    Oct 27, 2011 at 18:21
  • @Marc do you have any links to support your answer?
    – webdad3
    May 7, 2013 at 18:34
1

Im not sure if this is part of your concerns, but if you use TransactionScope you can pass in a TransactionOption that will deal with multiple transactions.

Check out TransactionOption.Isolationlevel

1
  • Not really sure if it would help in this scenario but I appreciate your attempt, I'll check it out.
    – BSarkis
    Oct 26, 2011 at 17:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.