我正在尝试使用Dapper与现有数据库格式进行交互,该数据库格式的表格的持续时间编码为BIGINT列中的刻度.在插入和读取数据库时,如何告诉Dapper将我的POCO的TimeSpan类型属性映射到滴答?
我试图将TimeSpan的类型映射设置为DbType.Int64:
sqlMapper.AddTypeMap(typeof(TimeSpan),DbType.Int64);
我还创建了一个ITypeHandler,但从未调用过SetValue方法:
public class TimeSpanToTicksHandler : sqlMapper.TypeHandler<TimeSpan> { public override TimeSpan Parse(object value) { return new TimeSpan((long)value); } public override void SetValue(IDbDataParameter parameter,TimeSpan value) { parameter.Value = value.Ticks; } }
这是我的POCO:
public class Task { public TimeSpan Duration { get; set; } // etc. }
执行这样的简单插入语句时:
string sql = "INSERT INTO Tasks (Duration) values (@Duration);";
并将POCO作为要插入的对象传递:
Task task = new Task { Duration = TimeSpan.FromSeconds(20) }; connection.Execute(sql,task);
我得到这个例外:
System.InvalidCastException : Unable to cast object of type 'System.TimeSpan' to type 'System.IConvertible'. at System.Convert.ToInt64(Objectvalue,IFormatProviderprovider) at System.Data.sqlite.sqliteStatement.BindParameter(Int32index,sqliteParameterparam) at System.Data.sqlite.sqliteStatement.BindParameters() at System.Data.sqlite.sqliteCommand.BuildNextCommand() at System.Data.sqlite.sqliteCommand.GetStatement(Int32index) at System.Data.sqlite.sqliteDataReader.NextResult() at System.Data.sqlite.sqliteDataReader..ctor(sqliteCommandcmd,CommandBehaviorbehave) at System.Data.sqlite.sqliteCommand.ExecuteReader(CommandBehaviorbehavior) at System.Data.sqlite.sqliteCommand.ExecuteNonQuery(CommandBehaviorbehavior) at System.Data.sqlite.sqliteCommand.ExecuteNonQuery() at Dapper.sqlMapper.ExecuteCommand(IDbConnectioncnn,refCommandDefinitioncommand,Action`2paramReader) in sqlMapper.cs: line 3310 at Dapper.sqlMapper.ExecuteImpl(IDbConnectioncnn,refCommandDefinitioncommand) in sqlMapper.cs: line 1310 at Dapper.sqlMapper.Execute(IDbConnectioncnn,Stringsql,Objectparam,IDbTransactiontransaction,Nullable`1commandTimeout,Nullable`1commandType) in sqlMapper.cs: line 1185
如果我按原样保留TimeSpan类型映射(默认为DbType.Time),它会写入TimeSpan的字符串版本,即“00:00:20.000”,这没有用,因为它与格式不匹配列中的其他数据.
解决方法
你可以做以下事吗?
public class Task { public TimeSpan Duration { get; set; } public long Ticks { get { return Duration.Ticks; } set { Duration = new TimeSpan(value); } } // etc. } string sql = "INSERT INTO Tasks (Duration) values (@Ticks);";