views:

249

answers:

2

We plan on using identity columns in our sql server database. Currently we are using guids to generate unique ids, but it turns out that the ordering is relevant so we consider switching to identity columsn.

Since ordering is relevant we want to make sure that the order in which we add objects to the entity context is also the order in which they are inserted into the database. This is relevant since sql server will be generating values for the identity column.

Is this guaranteed by the entity framework? If not, what is an efficient solution to generating your own unique integer ids for a database that is being updated from different processes.

+1  A: 

I wouldn't rely on the insert order as the order of your records returned. Sure, it'll work most of the time, but what if you ever need to insert a row somewhere? I'd say your best bet is to add an ordinal column and actively generate ordinals for each row as you'd like them to be returned.

D. Patrick
I am planning on adding an identity column to explicitly set the ordering. However the order that we want to put in there is the arrival sequence. I am looking for a solution that possibly avoids querying the database for the last added row in order to derive a new id for the new row.
Jeroen Huinink
Well, there are definitely other ways to do it without having to hit the database. For example, you could put a timestamp in there. If you have a lot of rows going in at the same time, you could have timestamp + transaction index. If you don't want to do that, you can have a bigint that stores ticks . . . it's pretty tough to get more than one insert per tick.Basically, you can have a time based ordinal if you need one. Then, if you need reorder for any reason, you still have that option.
D. Patrick
+1  A: 

I am just guessing here (although it should be pretty easy to test), but I don't think EF can guarantee the order. I am pretty sure that the internal structure is based on an IEnumerable type, probably a List, which are just enumerated during insert, and enumeration is as far as I know not guaranteed to be in the same order every time.

I would instead add a dedicated "sort order" column to your database table and take it form there.

Egil Hansen