我有以下代码(示例简化了一点):
public class Entity
{
public int Id { get; set; }
public TimeSpan Duration { get; set; }
...
}
...
public void Save(Entity e)
{
if (e.Id == 0)
_connection.Insert(e);
else
_connection.Update();
}
数据库是Sql Server 2008R2,而Duration字段是Time sql数据类型。
当我在新实体上调用Save时,即Id为0,则insert语句成功。在现有实体上调用Save时,我得到例外:
System.InvalidCastException occurred
HResult=-2147467262
Message=Failed to convert parameter value from a TimeSpan to a DateTime.
Source=TechTalk.SpecFlow
StackTrace:
at System.Data.SqlClient.SqlParameter.CoerceValue(Object value, MetaType destinationType, Boolean& coercedToDataFeed, Boolean& typeChanged, Boolean allowStreaming)
at System.Data.SqlClient.SqlParameter.GetCoercedValue()
at System.Data.SqlClient.SqlParameter.Validate(Int32 index, Boolean isCommandProc)
at System.Data.SqlClient.SqlCommand.BuildParamList(TdsParser parser, SqlParameterCollection parameters)
at System.Data.SqlClient.SqlCommand.BuildExecuteSql(CommandBehavior behavior, String commandText, SqlParameterCollection parameters, _SqlRPC& rpc)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at Dapper.SqlMapper.ExecuteCommand(IDbConnection cnn, IDbTransaction transaction, String sql, Action`2 paramReader, Object obj, Nullable`1 commandTimeout, Nullable`1 commandType) in c:\Dev\Dapper\Dapper NET40\SqlMapper.cs:line 2034
at Dapper.SqlMapper.Execute(IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Nullable`1 commandTimeout, Nullable`1 commandType) in c:\Dev\Dapper\Dapper NET40\SqlMapper.cs:line 730
at DapperExtensions.DapperImplementor.Update[T](IDbConnection connection, T entity, IDbTransaction transaction, Nullable`1 commandTimeout) in c:\Data\Projects\Nuget Projects\DapperExtensions\DapperExtensions\DapperImplementor.cs:line 140
我安装了最新的Dapper和DapperExtensions的NuGet版本。
为什么插入成功,而更新没有?我有可以使用的解决方法吗?
到目前为止,我已经手动创建了要调用的更新sql,但这远非理想。这个简单的例子有效:
_connection.Execute("update Entity set Duration=@Duration, ... where Id=@Id",
new {
e.Id,
e.Duration,
...
});