Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the next Primary Key for SQL 2008 in Entity Framework 4

I am using an Entity Framework 4 connection to connect to a SQL 2008 server to do database handling for my application.

I am using C# in Visual Studio 2010 and my question is regarding Primary Key fields that are incremented by the SQL itself, is it possible at all for me to be able to find the ID that will be used next by the database.

The reason why I cannot just find the last item and +1 is because if my table contains items 1,2,3,4 and 5, removing item 5 then adding another will make the next item become item 6, rather than 5 again (As I use the Identity Specification in SQL, but this must be used).

I cannot find any method such as Item.ID.GetNextIdentity() or something like that and have looked through as many similar questions like this but to no avail.

Any help would be appreciated

like image 995
JakeJ Avatar asked Aug 12 '11 09:08

JakeJ


1 Answers

There is no reliable way to use auto incremented ID and show it in a form before you do the save. That is wrong architecture. If you want to have ID shown before saving the form you must either:

  • Not use auto incremented column as ID and handle uniqueness yourselves
  • Save the form immediately when user starts creating it in some initial empty state and the final form confirmation will do only update

Why you cannot ask for next ID? Because if you do it in any way nobody says that received ID will be really used for your form. If another process / thread / application inserts form between your ID retrieval and your form persistence, the Id you shown will be assigned to that inserted form.

Also if you are using auto incremented primary keys in the database you cannot assign the key value in your application - the value will not be used and database can override it with its own.

like image 97
Ladislav Mrnka Avatar answered Sep 28 '22 14:09

Ladislav Mrnka