获取linq中表的CURRENT IDENTITY值。 [英] Get CURRENT IDENTITY value of a table in linq.

查看:75
本文介绍了获取linq中表的CURRENT IDENTITY值。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我正在使用C#/ .NET应用程序,我需要使用LINQ获取表的当前标识值。或者我可以使用sql查询通过使用 var num = DataContext.ExecuteCommand(Select IDENT_CURRENT('table')); ,通过使用来完成任务这段代码,我得到的值= -1。



var num = DataContext.ExecuteQuery< short>((Select IDENT_CURRENT( 'table'));< / short> ,通过使用此代码,我收到异常指定的强制转换无效。并且值仍为NULL。如果我做错了,请纠正我。如果有更好的方法可以执行此任务,请告诉我。



感谢您的帮助提前。

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.

推荐答案

你可能会这样做:



You could probably do this instead:

select MAX(id) from table





编辑=====================



我刚刚遇到了一些事情。如果你是d在当前加载的dataContext中,您的代码将无法正常工作。您必须实际查询数据库而不是数据上下文对象。当您从数据库中获取数据集时,表的系统信息都不会随之返回。您将再次使用SQLCommand,或者将存储过程中的IDENT_CURRENT作为输出变量返回并存储,以便在需要时使用。



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.


使用此:

int lastrouteid = Convert.ToInt32(routingDbContext.Database.SqlQuery< decimal>(Select IDENT_CURRENT('Routing.RouteDescriptionTable'),new object [0])。FirstOrDefault());
use this:
int lastrouteid = Convert.ToInt32(routingDbContext.Database.SqlQuery<decimal>("Select IDENT_CURRENT ('Routing.RouteDescriptionTable')", new object[0]).FirstOrDefault());


这篇关于获取linq中表的CURRENT IDENTITY值。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆