Get Current Identity value of the table using LINQ.
-
Hi, I am working on a C#/.NET application where I need to get Current Identity value of the table using LINQ. Or else I can use the sql query to get the task done by either using var num = DataContext.ExecuteCommand("Select IDENT_CURRENT ('table')");, by using this code, i am getting the value = -1. or var num = DataContext.ExecuteQuery(("Select IDENT_CURRENT ('table')");, by using this code, I am getting an exception "Specified cast is not valid." and the value remains NULL. Correct me if I am doing something wrong. let me know if there are any better ways to do this task. my scenario is different where Last few records in the table are deleted.............So in that scenario i will not be getting the right value needed. presently 30 records --> Max(id) gives me 30 4 records added to the table---> Max(id) gives me 34 Now i am deleting the last 4 records added this means that Current Identity value will be 34 but when i do Max(id) it gives me 30 but the correct value is 34.right? Thanks for ur help in advance.
-
Hi, I am working on a C#/.NET application where I need to get Current Identity value of the table using LINQ. Or else I can use the sql query to get the task done by either using var num = DataContext.ExecuteCommand("Select IDENT_CURRENT ('table')");, by using this code, i am getting the value = -1. or var num = DataContext.ExecuteQuery(("Select IDENT_CURRENT ('table')");, by using this code, I am getting an exception "Specified cast is not valid." and the value remains NULL. Correct me if I am doing something wrong. let me know if there are any better ways to do this task. my scenario is different where Last few records in the table are deleted.............So in that scenario i will not be getting the right value needed. presently 30 records --> Max(id) gives me 30 4 records added to the table---> Max(id) gives me 34 Now i am deleting the last 4 records added this means that Current Identity value will be 34 but when i do Max(id) it gives me 30 but the correct value is 34.right? Thanks for ur help in advance.
See if one of these work:
int num = DataContext.ExecuteQuery<int>("SELECT IDENT_CURRENT('SomeTable')").First();
Int16 num = DataContext.ExecuteQuery<Int16>("SELECT IDENT_CURRENT('SomeTable')").First();Though, like somebody else said in one of your other cross-posts, this may not be the best way to go about doing this. The ideal way depends on how you are inserting records.
Driven to the ARMs by x86.