【问题标题】:Unable to cast object of type 'System.Collections.Generic.List`1[System.Object] in Dapper无法在 Dapper 中转换 \'System.Collections.Generic.List`1[System.Object] 类型的对象
【发布时间】:2023-02-21 09:21:20
【问题描述】:

我可以使用 Dapper 从数据库中获取数据。但是当我尝试将其转换为 IEnumerable 时,出现错误:

System.InvalidCastException: 'Unable to cast object of type 'System.Collections.Generic.List`1[System.Object]' to type 'System.Collections.Generic.List`1[ITMS.Shared.Incident]'.'

请看我是如何实现数据获取的:

public async Task<IEnumerable<Incident>> GetIncidents(string authorId)
{
    try
    {
        using var connection = new SqlConnection(connectionString);
        var parameters = new DynamicParameters();
        parameters.Add("@Mode", 3);
        parameters.Add("@AuthorId", authorId);
        var incidents = await connection.QueryAsync(
            sql,
            param: parameters,
            commandType: CommandType.StoredProcedure);
        return (IEnumerable<Incident>)incidents; => I GET THE ERROR HERE
    }
    catch (Exception ew)
    {
        throw;
    }
}

我的查询只是一个直接的 SELECT 语句。

【问题讨论】:

    标签: c# dapper


    【解决方案1】:

    您应该使用QueryAsync&lt;T&gt;() 方法以返回IEnumerable&lt;T&gt;QueryAsync() 支持返回IEnumerable&lt;object&gt; 的动态类型。

    参考:Querying Multiple Rows With Dapper

    var incidents = await connection.QueryAsync<Incident>(
                sql,
                param: parameters,
                commandType: CommandType.StoredProcedure);
    
    return incidents;
    

    【讨论】:

    • 你是绝对正确的。谢谢。
    • 我会在 2 分钟后将其标记为已回答
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-14
    • 2014-01-29
    • 2021-01-29
    • 2021-11-17
    • 1970-01-01
    • 2014-03-14
    • 2012-05-22
    相关资源
    最近更新 更多