欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Dapper Object must implement IConvertible.

程序员文章站 2022-06-22 13:38:23
Dapper查询抛错误 Object must implement IConvertible.原因Dapper根据查询语句中的查询列名集合缓存将查询的结果映射为实体的方法。也就是说,如果查询的列数量、名称等相同,不管是不是同一个表,所有查询结果映射到为第一次查询的实体,后续的查询在读取查询结果后,在转换为指定T实体时报错。解决方案查询字段(名词、数量)和实体保持唯一错误信息System.InvalidCastException : Object must implement IConverti...

Dapper查询抛错误 Object must implement IConvertible.

原因

Dapper根据查询语句中的列名集合缓存映射实体方法
也就是说,如果查询的列数量、名称等相同,不管是不是同一个表、实体,所有查询映射为同一个实体,如果查询结果T不为缓存的实体,在转换时就会报错。

解决方案

查询中字段(名词、数量)和实体保持一对一关系

错误信息

System.InvalidCastException : Object must implement IConvertible.
错误信息

 消息: 
    System.InvalidCastException : Object must implement IConvertible.
  堆栈跟踪: 
    Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
    SqlMapper.QueryImpl[T](IDbConnection cnn, CommandDefinition command, Type effectiveType)+MoveNext() 行 1105
    List`1.ctor(IEnumerable`1 collection)
    Enumerable.ToList[TSource](IEnumerable`1 source)
    SqlMapper.Query[T](IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Boolean buffered, Nullable`1 commandTimeout, Nullable`1 commandType) 行 721
    SqlMapperExtensions.GetPageAll[T](IDbConnection connection, Int32 page, Int32 perPageSize, Expression`1 sortPredicate, ISpecification`1 specification, Boolean isAsc, IDbTransaction transaction, Nullable`1 commandTimeout) 行 340
    DapperRepositoryContext.GetPage[TEntity,TKey](Int32 page, Int32 perPageSize, Expression`1 sortPredicate, Boolean isAsc, ISpecification`1 specification) 行 259
    RepositoryBase`2.GetPage(Int32 page, Int32 perPageSize, Expression`1 sortPredicate, Boolean isAsc, ISpecification`1 specification) 行 287
    RepositoryBaseTests.GetPageTest() 行 617

抛错代码示例

public class TableAction
{
     public string Guid { get; set; }

     public string Code { get; set; }    

     public string Name { get; set; }   

 }
 public class TableObject
 {
     public string Guid { get; set; }

     public string Code { get; set; }

     public string Name { get; set; } 

     public string Description { get; set; }
 }

using (var conn = new Npgsql.NpgsqlConnection("User ID=postgres;Password=Bio!@#456;Host=192.168.1.182;Port=5432;Database=bup_dips;Pooling=true;"))
{
	conn.Open();
	var sql_action = "select guid , code ,name from bup_t_action limit 1;";
	var sql_object = "select guid , code ,name from bup_t_action_object  limit 1;";
	//下面这句能执行成功
	var tableAction = await conn.QueryFirstAsync<TableAction>(sql_action);
	
	//这句执行失败
	var tableObject = await conn.QueryFirstAsync<TableObject>(sql_object);
	/*  消息: 
	    System.InvalidCastException : Object must implement IConvertible.
	  堆栈跟踪: 
	    Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
	    SqlMapper.QueryRowAsync[T](IDbConnection cnn, Row row, Type effectiveType, CommandDefinition command) 行 508
	    RepositoryBaseTests.GetPageTest() 行 632
	    --- End of stack trace from previous location where exception was thrown ---
	    */
}	

原因分析-Dapper源码解读

执行查询

执行查询前会缓存中获取转换方法,如果没有在创建,后面会看到缓存Key为查询字段,暂时只知道读取缓存就好

var identity = new Identity(command.CommandText, command.CommandType, cnn, effectiveType, param?.GetType());

var info = GetCacheInfo(identity, param, command.AddToCache);

Dapper Object must implement IConvertible.

转换方法

序列化方法的实例是个结构体

 private struct DeserializerState
 {
      public readonly int Hash;
      public readonly Func<IDataReader, object> Func;

      public DeserializerState(int hash, Func<IDataReader, object> func)
      {
          Hash = hash;
          Func = func;
      }
  }

Dapper Object must implement IConvertible.
Dapper Object must implement IConvertible.
Dapper Object must implement IConvertible.

Key

Dapper Object must implement IConvertible.

Value

Dapper Object must implement IConvertible.

总结

while (reader.Read())
{
    object val = func(reader);
    //reader相同返回列,object val始终为最先执行的class:假设为A(class)
    //如果T为A ,则 val == null || val is T 为 true,能够强转成功
    if (val == null || val is T)
    {
        yield return (T)val;
    }
    //后执行的查询,假设对象T不是A,就会在这里报错
    //Convert.ChangeType转换失败
    //将A强转为T(类B、类C、类D)抛出错误
    //System.InvalidCastException : Object must implement IConvertible.
    else
    {
        yield return (T)Convert.ChangeType(val, convertToType, CultureInfo.InvariantCulture);
    }
}

本文地址:https://blog.csdn.net/yiquan_yang/article/details/107341252