How should I handle maintaining row Identity for new records in Linq / Entity Framework?

457 Views Asked by At

What is the proper way to create a new unique shared key when using Linq and EF with SQL?

I could use a GUID upon inserting the record but I only want want my keys to have 7 digits or characters in it as they will appear in the URL of my MVC application. If this isn't an option, or it's just better with GUID's let me know.

1

There are 1 best solutions below

4
On BEST ANSWER

If you do not need a unique key across machine boundaries then I would just go with a bigint/idenity that auto-increments by 1 (which is the default). You do not have to specify the identity when adding a new entity with EF, it will be auto-assigned. Once it has been assigned you can then use it as a FK.

In my opinion GUIDs are only useful in this context if you have to guarantee that the key is unique across multiple databases, i.e. you create they key on one machine (A) and want to transfer the data to another machine (B), retaining the key. This is not possible with bigint keys since machine B might have inserted other data with the same key already.