【问题标题】:Database.ExecuteSqlCommand returns incorrect rowcountDatabase.ExecuteSqlCommand 返回不正确的行数
【发布时间】:2014-12-15 17:59:40
【问题描述】:

我正在使用 context.Database.ExecuteSql 来更新表。正确执行带有 where 子句的更新并更新记录。但是,该方法为 rowcount 返回 2 而不是 1。当我在 SSMS 中执行 update 语句时,返回的结果 rowcount 为 1。有人可以对此提供见解吗?

            string query =
            string.Format("update {0} set Description = '{1}', Code = '{2}', LastUpdatedBy = '{3}', LastUpdatedDate = '{4}' where ID = {5};",
                tableName,
                description,
                code,
                lastUpdatedBy,
                lastUpdatedDate,
                ID);

        int rowCount = 0;
        string message = string.Empty;

        using (DBContext context = new DBContext())
        {
            rowCount = context.Database.ExecuteSqlCommand(TransactionalBehavior.EnsureTransaction, query);
        }

        return rowCount == 0 ?  //this return 2 instead of 1.
            new SaveResult(SaveResult.MessageType.Error, string.Format("There was an error updating a record in the {0} table.", tableName), "Index") :
            new SaveResult(SaveResult.MessageType.Success, string.Format("The update of {0} was successful.", tableName), "Index");

这会在 SSMS 中返回 rowcount = 1:

update zAddressTypes 
set Description = 'Current', Code = '101122', LastUpdatedBy = 'user', LastUpdatedDate = '10/20/2014 12:17:26 PM' 
where ID = 1; 

DECLARE @RowCount INTEGER = @@ROWCOUNT; 
select @RowCount;

【问题讨论】:

    标签: entity-framework-6 dml


    【解决方案1】:

    单独返回行数。您在这里看到的是查询的退出状态。

    ExecuteSqlCommand 返回值是查询的状态而不是行数。您可能想考虑使用数据读取器或类似的东西来返回行数。

    【讨论】:

    • 谢谢你,这就解释了。
    • 这是不正确的。检查 MS 文档。返回值是“执行命令后数据库返回的结果”,如 MS 文档中所述,docs.microsoft.com/en-us/dotnet/api/…
    【解决方案2】:

    这是数据上下文的工作方式,请参阅此链接: Entity Framework: Database.ExecuteSqlCommand Method 显然该命令正在更新两条记录。

    【讨论】:

    • 因触发器而更新的行也包含在受影响的行数中。
    【解决方案3】:

    你的桌子上有触发器吗?我确认此行为可能是由触发器引起的,因为受触发器影响的行被添加到受 SQL 命令影响的行数中。我通常检查 0 或 >0 返回值以了解是否有任何影响。如果您正在调用存储过程,也可以返回一个输出变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-09
      • 2019-11-22
      • 1970-01-01
      • 2015-09-25
      相关资源
      最近更新 更多