精巧和向下整数转换

时间:2014-05-16 13:25:44

标签: sqlite dapper system.data.sqlite

我通过System.Data.Sqlite通过Sqlite查看Dapper的v1.25。如果我运行此查询:

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

我收到以下错误:System.InvalidCastException: Specified cast is not valid

这是因为Sqlite将上述值作为Int64返回,我可以使用以下代码进行验证。这将抛出&#34; Int64&#34;:

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

现在,以下代码实际上将处理从Int64到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());

当我抛出此异常时,它会给我实际的行数,表明Dapper为我处理了转换。

我的问题是,为什么dbc.Query<int>无法以与dbc.Query<QuerySummary>类似的方式处理向下转换?这是预期的行为吗?

1 个答案:

答案 0 :(得分:4)

不,这不是故意的。我已经提交并推送更改到github,这使得以下传递(它在1.25失败);它应该很快出现在NuGet上:

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