2014-10-20 65 views
0

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

  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 = 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; 

回答

1

rowcount被单独返回。你在这里看到的是查询的退出状态。

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

+0

谢谢,这解释了它。 – 2015-08-27 14:07:13