2014-10-20 58 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