无法在 Dapper 中转换类型为“System.Collections.Generic.List”1[System.Object] 的对象

问题描述 投票:0回答:1

我可以很好地使用 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个回答
1
投票

你应该使用

QueryAsync<T>()
方法来返回
IEnumerable<T>
QueryAsync()
支持返回
IEnumerable<object>
.

的动态类型

参考:使用 Dapper 查询多行

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

return incidents;
© www.soinside.com 2019 - 2024. All rights reserved.