Click here to Skip to main content
15,911,707 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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<short>(("Select IDENT_CURRENT ('table')");</short>, 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.

Thanks for ur help in advance.
Posted
Updated 29-Jun-11 6:45am
v4

You could probably do this instead:

SQL
select MAX(id) from table


EDIT =====================

Something just occurred to me. If you're doing this in a currently loaded dataContext, your code won't work. You have to actually query the database as opposed to your data context object. When you get a dataset back from the database, none of the table's system info comes back with it. You're going to HAVE to use SQLCommand again, or return the IDENT_CURRENT from the stored procedure as an output variable and store that for use when it's needed.
 
Share this answer
 
v2
Comments
madhubabu 29-Jun-11 13:52pm    
Thanks for the reply.........but 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?
#realJSOP 29-Jun-11 14:49pm    
I see your point. See my edit.
use this:
int lastrouteid = Convert.ToInt32(routingDbContext.Database.SqlQuery<decimal>("Select IDENT_CURRENT ('Routing.RouteDescriptionTable')", new object[0]).FirstOrDefault());
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900