Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to cast object of type 'System.Collections.Generic.List`1[System.Object] in Dapper

I can get data from the database using Dapper fine. But when I try to cast it into an IEnumerable, I get the error:

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]'.'

Please see how I implement the fetching of data:

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;
    }
}

My query is just a straight forward SELECT Statement.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You should use QueryAsync<T>() method in order to return IEnumerable<T>. QueryAsync() supports dynamic type which returns IEnumerable<object>.

Reference: Querying Multiple Rows With Dapper

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

return incidents;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading