在LINQ中执行SQL时返回id字段

发布于 2024-11-06 09:15:49 字数 534 浏览 0 评论 0原文

我正在尝试使用 LINQ 执行 SQL 插入查询并返回 ID 字段。我的代码不起作用,有人可以告诉我我的语法是否错误吗?

string query = "insert into EnvironmentalReportDepts ";
                query += "(fkDeptID, OrderNumber, fkEnvironmentalReportID) ";
                query += "values(" + tmpDeptReport.fkDeptID + ", " + tmpDeptReport.OrderNumber + ", " + tmpDeptReport.EnvironmentalReport.EnvironmentalReportID + ") ";
                query += "select scope_identity()";

                var newDeptID = _database.ExecuteQuery<int>(query).ToList()[0];

I'm trying to execute an SQL insert query using LINQ and returning the ID field. My code does not work, can anybody tell me if my syntax is wrong?

string query = "insert into EnvironmentalReportDepts ";
                query += "(fkDeptID, OrderNumber, fkEnvironmentalReportID) ";
                query += "values(" + tmpDeptReport.fkDeptID + ", " + tmpDeptReport.OrderNumber + ", " + tmpDeptReport.EnvironmentalReport.EnvironmentalReportID + ") ";
                query += "select scope_identity()";

                var newDeptID = _database.ExecuteQuery<int>(query).ToList()[0];

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

却一份温柔 2024-11-13 09:15:49

尝试更改

query += "select scope_identity()";

query += "; select scope_identity()";

另外,您可能必须使用

 _database.ExecuteQuery<decimal>(query).ToList()[0];

Try changing

query += "select scope_identity()";

to

query += "; select scope_identity()";

Also, you may have to use

 _database.ExecuteQuery<decimal>(query).ToList()[0];
三生一梦 2024-11-13 09:15:49

将查询更改为:

string query = "DECLARE @scope_identity int"; 
query += "insert into EnvironmentalReportDepts ";               
query += "(fkDeptID, OrderNumber, fkEnvironmentalReportID) ";                 
query += "values(" + tmpDeptReport.fkDeptID + ", " + tmpDeptReport.OrderNumber + ", " + tmpDeptReport.EnvironmentalReport.EnvironmentalReportID + ") ";
query += "SET @scope_identity=@@IDENTITY";                 
query += "select @scope_identity"; 

change query to:

string query = "DECLARE @scope_identity int"; 
query += "insert into EnvironmentalReportDepts ";               
query += "(fkDeptID, OrderNumber, fkEnvironmentalReportID) ";                 
query += "values(" + tmpDeptReport.fkDeptID + ", " + tmpDeptReport.OrderNumber + ", " + tmpDeptReport.EnvironmentalReport.EnvironmentalReportID + ") ";
query += "SET @scope_identity=@@IDENTITY";                 
query += "select @scope_identity"; 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文