c# - 从 TableAdapter 获取@@IDENTITY

标签 c# asp.net sql tableadapter

我正在尝试完成一个看似简单的任务,但实际上却变成了几个小时的冒险:从 TableAdapter.Insert() 获取 @@Identity

这是我的代码:

protected void submitBtn_Click(object sender, EventArgs e)
{
    AssetsDataSetTableAdapters.SitesTableAdapter sta = new AssetsDataSetTableAdapters.SitesTableAdapter();
    int insertedID = sta.Insert(siteTxt.Text,descTxt.Text);

    AssetsDataSetTableAdapters.NotesTableAdapter nta = new AssetsDataSetTableAdapters.NotesTableAdapter();
    nta.Insert(notesTxt.Text, insertedID, null,null,null,null,null,null);
    Response.Redirect("~/Default.aspx");
}

一个 answer 建议我可能要做的就是更改 ExecuteMode。我试过了。这使得 GetData() 停止工作(因为我现在返回的是标量而不是行数据)(我需要保留 GetData())。它也没有解决 insertedID 变量仍设置为 1 的问题。

我尝试在 TypedDataSet.XSD 中创建第二个 TableAdapter 并将该适配器的属性设置为“标量”,但变量获取值仍然失败共 1 个。

生成的插入命令为

INSERT INTO [dbo].[Sites] ([Name], [Description]) VALUES (@Name, @Description);
SELECT Id, Name, Description FROM Sites WHERE (Id = SCOPE_IDENTITY())

并且还设置了“刷新数据表”(在 Insert 和 Update 语句之后添加一个 select 语句以检索标识)。

环境

SQL Server 2008 R2、Visual Studio 2010、.NET 4、Windows XP,所有本地同一台机器。

这是什么原因造成的?

编辑/更新

我想澄清一下,我在 Visual Studio 中使用自动生成的代码。我不知道生成代码的“工具”是什么,但是如果您双击 *.XSD 文件,它会显示 SQL 表架构和关联的 TableAdapter 的 UI。我想继续使用自动生成的代码并以某种方式启用获取身份。我不想用存储过程手工编写这一切。

最佳答案

真正的答案:

  • 阅读下面的注释!

Get identity from tableadapter insert function

I keep getting questions about this issue very often and never found time to write it down.

Well, problem is following: you have table with primary key with int type defined as Identity and after insert you need to know PK value of newly inserted row. Steps for accomplishing to do this are following:

use wizard to add new insert query (let's call it InsertQuery) in the body of query just add SELECT SCOPE_IDENTITY() at the bottom after saving this query, change ExecuteMode property of this query from NonQuery to Scalar in your code write following (ta is TableAdapter instance) :

int id;

try
{
 id = Convert.toInt32(ta.InsertQuery(firstName, lastName, description));
}
catch (SQLException ex)
{
//...
}
finally
{
//...
}

Make money with this! :) Posted 12th March 2009 by Draško Sarić

From: http://quickdeveloperstips.blogspot.nl/2009/03/get-identity-from-tableadapter-insert.html

注意事项:

  • 可以通过生成的插入查询的属性将 ExecutMode 设置为 Scalar。 (按 F4)。

  • 在我的版本 (Visual Studio 2010 SP1) 中,选择语句是自动生成的。

关于c# - 从 TableAdapter 获取@@IDENTITY,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3704394/

相关文章:

c# - 获取枚举值作为字符串数组

c# - 在 C# 中编译表单

asp.net - ASP.NET网站升级了VS08-VS10,现在直到我在运行时请求页面时才会显示编译时错误

sql - 左连接与第二个表中的不同值

c# - 在不更改文本、背景颜色、已启用的情况下突出显示按钮?

c# - 使用通用 convert 方法在抽象类的不同实现之间进行转换

asp.net - ASP.NET 中的 UWP API

asp.net - 在 Fiddler 中看不到 WebClient post 请求

Mysql分组计数日期范围内的数据行

sql - 无法在查询中执行 DML 操作