I am trying to use LINQ to create a new record in a predefined (in production) table where the ID isnt IDENTITY.
I've seen the previous answers about using SQL and transaction to solve this: Best way to get the next id number without "identity"
My question is if there is a LINQ / C# version of this too as I would like to have a function in C# that I can place in code with the rest of the functions.
For the record, we are using old SQL-server 2000 so no native .NET support inside the server.
EDIT
I was hoping someone would show the actual C# / LINQ code for it. Something about SELECT TOP 1 [TABLE_ID] ORDER BY DESC and then adding 1 to the value in TABLE_ID... but perha开发者_Python百科ps its a question that is too hard?
The reason for using a SQL-side identity is that SQL can control any parallelism issues. If two users call you C# identity code at the same time, you might end up with two IDs the same.
To work around this, either go with SQL identity, or generate GUIDs instead of sequential IDs.
These are very standard and common things to do, and there's not a lot of point doing anything else, as you'll have to deal with concurrency pain that's already been solved.
Having said that, you can do the obvious:
INSERT INTO my_table (id, ...)
VALUES ((SELECT MAX(id)+1 FROM my_table), ...)
Or something similar IF AND ONLY IF you set the table/transaction locking VERY carefully.
I think the best idea is when you open the page on Page_Load
create a new record/row in the table
then you can show the created id as the item id then when is the user submits the form then update that record with the all info.
You can schedule a job to clear the empty data if for example the user open the new page but decided not to continue and don't submit the form based on whatever condition you want (you might use bit as a condition for submitted or not).
精彩评论