views:

37

answers:

3

Hi,

From what I gather, Linq to SQL doesn't actually execute any database commands (including the opening of database connections) until the SubmitChanges() method is called. If this is the case, I would like to increase the efficiency of a few methods. Is it possible for me to retrieve the ID of an object before inserting it? I'd rather not call SubmitChanges() twice, if it's possible for me to know the value of the ID before it's actually inserted into the database. From a logical point of view, it would only makes sense to have to open a connection to the database in order to find out the value, but does an insertion procedure also have to take place?

Thanks

A: 

Well, here is the problem: You get somehow id BEFORE inserting to database, and do some processing with it. In the same time another thread does the same, and get's the same ID, you've got a conflict.

I.e. I don't think there is an easy way of doing this.

BarsMonster
I had a feeling this would be the case. Is there a way of having a database connection open and reserve the ID (as if it's been taken), but not actually perform an insertion? Any other threads would see it as taken and return the next free ID.
keyboardP
+1  A: 

The usual technique to solve this, is to generate a unique identifier in the application layer (such as a GUID) and use this as the ID. That way you do not have to retrieve the ID on a subsequent call.

Of course, using a GUID as a primary key can have it's drawbacks. If you decide to go this way look up COMB GUID.

Mitch Wheat
Thanks for the heads up on the COMB GUID. I haven't come across those, so will have a read through.
keyboardP
A: 

I don't necessarily recommend this, but have seen it done. You can calculate your own ID as an integer using a stored procedure and a table to hold the value of the next ID. The stored procedure selects the value from the table to return it, then increments the value. The table will look something like the following

Create Table Keys(
name varchar(128) not null primary key,
nextID int not null
)

Things to note before doing this is that if you select and then update in 2 different batches you have potential key collision. Both steps need to be treated as an atomic transaction.

doug_w