c# – 在SQLite和Dapper中映射TimeSpan
发布时间:2020-12-15 07:40:32 所属栏目:百科 来源:网络整理
导读:我正在尝试使用Dapper与现有数据库格式进行交互,该数据库格式的表格的持续时间编码为BIGINT列中的刻度.在插入和读取数据库时,如何告诉Dapper将我的POCO的TimeSpan类型属性映射到滴答? 我试图将TimeSpan的类型映射设置为DbType.Int64: SqlMapper.AddTypeMap
我正在尝试使用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);"; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |