成功插入期间 SqlDataAdapter 未触发 RowUpdated 或 RowUpdating
Posted
技术标签:
【中文标题】成功插入期间 SqlDataAdapter 未触发 RowUpdated 或 RowUpdating【英文标题】:SqlDataAdapter not firing RowUpdated or RowUpdating during successful Insert 【发布时间】:2012-06-01 07:53:39 【问题描述】:我有以下代码:
DataSet dataSet = new DataSet();
bool result;
using (SqlConnection connection = new SqlConnection(command.Connection.ConnectionString))
connection.Open();
SqlDataAdapter adapter = new SqlDataAdapter(command);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
adapter.RowUpdated += OnRowUpdated;
adapter.RowUpdating += AdapterOnRowUpdating;
adapter.Fill(dataSet);
// Code to modify data in the DataSet here.
// Without the SqlCommandBuilder, this line would fail.
adapter.UpdateCommand = builder.GetUpdateCommand();
int i = adapter.Update(dataSet);
result = i > 0;
return result;
此代码假设获取我的 SqlCommand 对象并将其提交给 SqlDataAdapter 的更新方法。 SqlCommand 可以是使用 adapter.Update() 方法执行的 INSERT、UPDATE 或 DELETE。
命令执行成功,但 adapter.Update() 方法返回 0 行。我检查了数据库,我可以看到它是成功的。 RowUpdated 和 RowsUpdating 事件也不会触发。我不确定发生了什么事。请帮忙。
提前谢谢你。
编辑:
public void OnRowUpdated(object sender, SqlRowUpdatedEventArgs sqlRowUpdatedEventArgs)
switch (sqlRowUpdatedEventArgs.StatementType)
case StatementType.Insert:
case StatementType.Update:
case StatementType.Delete:
case StatementType.Batch:
if (sqlRowUpdatedEventArgs.Status != UpdateStatus.ErrorsOccurred)
SqlReporting.LogSqlCommand(sqlRowUpdatedEventArgs.Command);
break;
编辑: 我使用以下查询插入:
INSERT INTO Users
(Username, Firstname, Lastname, RoleId, ReceiveRoleAlerts, StatusId, Password, Fingerprint, AuthenticityCheck, CreatedByUserId, CreationDate, ModifiedByUserId,
ModificationDate)
SELECT @Username AS Expr1, @Firstname AS Expr2, @Lastname AS Expr3, @RoleId AS Expr4, @ReceiveRoleAlerts AS Expr5, @StatusId AS Expr6, @Password AS Expr7,
@Fingerprint AS Expr8, @AuthenticityCheck AS Expr9, @CreatedByUserId AS Expr10, @CreationDate AS Expr11, @ModifiedByUserId AS Expr12,
@ModificationDate AS Expr13
WHERE (NOT EXISTS
(SELECT Username, Firstname, Lastname, RoleId, ReceiveRoleAlerts, StatusId, Password, Fingerprint, AuthenticityCheck, CreatedByUserId, CreationDate,
ModifiedByUserId, ModificationDate
FROM Users AS Users_1
WHERE (Username = @Username)));
【问题讨论】:
【参考方案1】:使用
adapter.RowUpdating += new SqlRowUpdatingEventHandler(AdapterOnRowUpdating);
adapter.RowUpdated += new SqlRowUpdatedEventHandler(OnRowUpdated);
而不是
adapter.RowUpdated += OnRowUpdated;
adapter.RowUpdating += AdapterOnRowUpdating;
【讨论】:
感谢您的快速回复。我已经更改了代码以反映您的建议,但不幸的是它仍然是同样的问题。我得到一个成功的插入,但没有启动任何事件,并且即使插入成功,adapter.Update() 也会返回 0。 我使用的是 sql server 2008 express。我现在发布实现以上是关于成功插入期间 SqlDataAdapter 未触发 RowUpdated 或 RowUpdating的主要内容,如果未能解决你的问题,请参考以下文章
.Net SqlDataAdapter 在使用列上的默认值插入后检索身份