我们遇到一个问题,在有限的时间内每次方法调用都会发生。然后它按预期工作。问题是代码产生了两个WHERE子句。
我们正在使用Servicestack 4.5.14
我们拥有的方法:
protected static void InsertOrUpdate<T>(
IDbConnection connection,
T item,
Expression<Func<T, bool>> singleItemPredicate,
Expression<Func<T, object>> updateOnlyFields = null)
{
var type = item.GetType();
var idProperty = type.GetProperty("Id");
if (idProperty == null)
{
throw new Exception("Cannot insert or update on a class with no ID property");
}
var currentId = (int)idProperty.GetValue(item);
if (currentId != 0)
{
throw new Exception("Cannot insert or update with non-zero ID");
}
var query = connection.From<T>().Where(singleItemPredicate).WithSqlFilter(WithUpdateLock);
T existingItem;
try
{
existingItem = connection.Select(query).SingleOrDefault();
Log.Verbose(connection.GetLastSql);
}
catch (SqlException)
{
Log.Verbose(connection.GetLastSql);
throw;
}
if (existingItem == null)
{
Insert(connection, item);
return;
}
var existingId = (int)idProperty.GetValue(existingItem);
idProperty.SetValue(item, existingId);
try
{
var affectedRowCount = connection.UpdateOnly(item, onlyFields: updateOnlyFields, where: singleItemPredicate);
Log.Verbose(connection.GetLastSql);
if (affectedRowCount != 1)
{
throw new SwToolsException("Update failed");
}
}
catch (SqlException)
{
Log.Verbose(connection.GetLastSql);
throw;
}
}
当所有方法都起作用时,日志的示例输出可能是:
选择“ Id”,“应用程序”,“主机名”,“ LastContact”,“版本”,“ ToolState”,“ ServerState” FROM“ ca”。“ ExecutionHost” WITH(UPDLOCK)WHERE(“主机名” = @ 0)
更新“ ca”。“ ExecutionHost” SET“ LastContact” = @ LastContact,“ Version” = @ Version,“ ToolState” = @ ToolState,“ ServerState” = @ ServerState WHERE(“ Hostname” = @ 0)>
失败时,输出(同一会话,仅几秒钟后)为:
选择“ Id”,“应用程序”,“主机名”,“ LastContact”,“版本”,“ ToolState”,“ ServerState” FROM“ ca”。“ ExecutionHost” WITH(UPDLOCK)WHERE(“主机名” = @ 0)
更新“ ca”。“ ExecutionHost” SET“ LastContact” = @ LastContact,“ Version” = @ Version,“ ToolState” = @ ToolState,“ ServerState” = @ ServerState WHERE“ LastContact” = @ LastContact, “版本” = @版本,“工具状态” = @工具状态,“服务器状态” = @服务器状态在哪里(“主机名” = @ 0)
用粗体标记的是SQL的添加,使调用失败。似乎它在SET子句中添加了附加的WHERE子句。
我们已经调试了一段时间,并且真的不知道问题是在我们一方还是在Servicestack中。
关于继续前进的任何想法?