我通过System.Data.sqlite用sqlite检查Dapper的v1.25.如果我运行此查询:
var rowCount = dbc.Query<int>("SELECT COUNT(*) AS RowCount FROM Data").Single();
我收到以下错误:System.InvalidCastException:指定的强制转换无效
这是因为sqlite将上述值作为Int64返回,我可以使用以下代码进行验证.这将抛出“Int64”:
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> ;?的方式处理向下转换这是预期的行为吗?
不,这不是故意的.我已经提交并推送更改到github,这使得以下传递(它在1.25失败);它应该很快出现在NuGet上:
// https://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); }