Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dapper and Downward Integer Conversion

I am checking out v1.25 of Dapper with Sqlite via System.Data.Sqlite. If I run this query:

var rowCount = dbc.Query<int>("SELECT COUNT(*) AS RowCount FROM Data").Single();

I get the following error: System.InvalidCastException: Specified cast is not valid

This is because Sqlite returns the above value as an Int64, which I can verify with the following code. This will throw "Int64":

var row = dbc.Query("SELECT COUNT(*) AS RowCount FROM Data").Single();
Type t = row.RowCount.GetType();
throw new System.Exception(t.FullName);

Now, the following code will actually handle the downward conversion from Int64 to Int32:

public class QuerySummary
{
    public int RecordCount { get; set; }
}
var qs = dbc.Query<QuerySummary>("SELECT COUNT(*) AS RecordCount FROM Data").Single();
rowCount = qs.RecordCount;
throw new System.Exception(rowCount.ToString());

When I throw this exception, it gives me the actual row count, indicating that Dapper handled the conversion for me.

My question is, why is it that dbc.Query<int> does not handle the downward conversion in a similar way to dbc.Query<QuerySummary>? Is this intended behavior?

like image 818
John Avatar asked May 16 '14 13:05

John


1 Answers

No, that is not intentional. I've committed and pushed changes to github which make the following pass (it fails on 1.25); it should appear on NuGet at some point soon too:

    // http://stackoverflow.com/q/23696254/23354
    public void DownwardIntegerConversion()
    {
        const string sql = "select cast(42 as bigint) as Value";
        int i = connection.Query<HasInt32>(sql).Single().Value;
        Assert.IsEqualTo(42, i);

        i = connection.Query<int>(sql).Single();
        Assert.IsEqualTo(42, i);
    }
like image 200
Marc Gravell Avatar answered Oct 04 '22 20:10

Marc Gravell