数据集:如何捕获 SELECT SCOPE_IDENTITY() 返回的主键值?
我正在使用数据集。我有一个名为 PackageTableAdapter 的表适配器,其中包含一个名为 InsertPackage 的方法。
INSERT INTO [dbo].[Packages] ([UserID], [Name]) VALUES (@UserID, @Name)
//Return the PackageID value for the newly created record...
SELECT SCOPE_IDENTITY()
该表适配器正由中间层类使用,代码如下:
private PackagesTableAdapter _packagesTableAdapter = null;
protected PackagesTableAdapter Adapter
{
get
{
if (_packagesTableAdapter == null)
_packagesTableAdapter = new PackagesTableAdapter();
return _packagesTableAdapter;
}
}
public bool AddPackage(string PackageName)
{
// Create a new PackageRow instance
Album.PackagesDataTable packages = new AlbumCongo.PackagesDataTable();
Album.PackagesRow package = packages.NewPackagesRow();
// Add the new package
package.Name = PackageName;
packages.AddPackagesRow(package);
int rowsAffected = Adapter.Update(packages);
// Return true if precisely one row was inserted,
// otherwise false
return rowsAffected == 1;
}
如何捕获新创建的包的主键(应该由 SELECT SCOPE_IDENTITY() 语句返回的主键) )?
编辑
我不想返回 bool 值,而是返回一个自定义对象,其中包含 bool 值和表示新创建行的 ID 的 int。
谢谢你的帮助。
I'm using a dataset. I have a table Adapter called PackageTableAdapter, which contains a method called InsertPackage.
INSERT INTO [dbo].[Packages] ([UserID], [Name]) VALUES (@UserID, @Name)
//Return the PackageID value for the newly created record...
SELECT SCOPE_IDENTITY()
This table adapter is being used by a middle tier class, with the below code:
private PackagesTableAdapter _packagesTableAdapter = null;
protected PackagesTableAdapter Adapter
{
get
{
if (_packagesTableAdapter == null)
_packagesTableAdapter = new PackagesTableAdapter();
return _packagesTableAdapter;
}
}
public bool AddPackage(string PackageName)
{
// Create a new PackageRow instance
Album.PackagesDataTable packages = new AlbumCongo.PackagesDataTable();
Album.PackagesRow package = packages.NewPackagesRow();
// Add the new package
package.Name = PackageName;
packages.AddPackagesRow(package);
int rowsAffected = Adapter.Update(packages);
// Return true if precisely one row was inserted,
// otherwise false
return rowsAffected == 1;
}
How do I capture the primary key of the newly created package (the one that's supposed to returned by the SELECT SCOPE_IDENTITY() statement)?
EDIT
Instead of returning a bool value, I'd like to return a custom object that contains both the bool value and an int representing the ID of the newly created row.
Thanks for helping.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,您必须将插入方法的返回类型设为
Scaler
。您还可以通过右键单击插入方法属性
的属性来执行此操作。其次,您可以通过调用 Adapter 方法来获取 ID,如下所示:
First of all you have to make the return type of the insert method to
Scaler
. You can also do so by right clicking the properties of yourinsert Method properties
.Secondly you can get the ID by calling the
Adapter method
like this:在 Adapter.Update 调用之后检查 DataRow 对象上的 PackageID。
Check the PackageID on the DataRow object AFTER the Adapter.Update call.