如何使dapper在POCO中将SQL Server rowversion作为ulong处理?

时间:2019-05-24 10:22:13

标签: c# dapper

我见过this other question,这不是我的问题。

我正在使用Dapper multi-mapping处理两个对象之间的一对一关系。 我的两个表都使用rowversion列(时间戳)。

我正在使用的SQL查询是使用INNER JOIN进行的基本SELECT,正在为rowversion列返回一个字节数组。我想模仿EF Core指定字段转换的功能:

// https://github.com/aspnet/EntityFrameworkCore/issues/5936#issuecomment-397987482
 entity.Property(e => e.RowVersion)
     .HasConversion(new NumberToBytesConverter<ulong>())
     .IsRowVersion();

dapper映射失败,并出现以下错误:

System.Data.DataException
  HResult=0x80131501
  Message=Error parsing column 17 (RowVersion=System.Byte[] - Object)
  Source=Dapper.StrongName
  StackTrace:
   at Dapper.SqlMapper.ThrowDataException(Exception ex, Int32 index, IDataReader reader, Object value) in C:\projects\dapper\Dapper\SqlMapper.cs:line 3609
   at Dapper.SqlMapper.<>c__DisplayClass156_0`8.<GenerateMapper>b__0(IDataReader r) in C:\projects\dapper\Dapper\SqlMapper.cs:line 1542
   at Dapper.SqlMapper.<MultiMapImpl>d__153`8.MoveNext() in C:\projects\dapper\Dapper\SqlMapper.cs:line 1444
   at System.Collections.Generic.List`1.AddEnumerable(IEnumerable`1 enumerable)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at Dapper.SqlMapper.<MultiMapAsync>d__52`8.MoveNext() in C:\projects\dapper\Dapper\SqlMapper.Async.cs:line 949
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at TestDapper.Program.<RunSQLCommand>d__17`3.MoveNext() in C:\Users\olivier.matrot\dapper\Program.cs:line 544
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at TestDapper.Program.<RunSQLCommand>d__17`3.MoveNext() in C:\Users\olivier.matrot\dapper\Program.cs:line 561
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at TestDapper.Program.<Main>d__8.MoveNext() in C:\Users\olivier.matrot\dapper\Program.cs:line 374
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at TestDapper.Program.<Main>(String[] args)

Inner Exception 1:
InvalidCastException: Object must implement IConvertible.

我很确定内部异常消息不是解决之道。 任何帮助表示赞赏。

编辑


使用TypeHandler解决了它:

public class ULongTypeHandler : SqlMapper.TypeHandler<ulong>
{
    public override ulong Parse(object value)
    {
        return (ulong)new NumberToBytesConverter<ulong>().ConvertFromProvider(value);
    }

    public override void SetValue(IDbDataParameter parameter, ulong value)
    {
        throw new NotImplementedException();
    }
}

但这将适用于POCO上的所有ulong属性。

0 个答案:

没有答案