Xamarin下sqlite-net-pcl的Query<int>返回0但Query<Foo>正常问题
问题根因
sqlite-net-pcl的Query<T>方法依赖查询返回列名与泛型类型的属性名匹配完成值映射:
你执行SELECT Max(Id) FROM 表名时,返回的聚合列默认别名为Max(Id),而int是值类型没有对应名称的属性,框架无法完成赋值,因此返回默认值0。
你查询全表返回Foo类时,SELECT *返回的列名和Foo的属性名完全匹配,所以映射正常。
解决方案
方案1:使用专门的标量查询方法(最推荐)
ExecuteScalar<T>是sqlite-net-pcl专门用于返回单个查询值的API,不需要映射逻辑,性能最优:
public int GetLastInsertedId() { return conn.ExecuteScalar<int>($"SELECT Max(Id) FROM {typeof(T).Name}"); }
方案2:使用last_insert_rowid()获取最新插入ID(插入后立即取值的场景更推荐)
SQLite内置的last_insert_rowid()函数会返回当前连接最后插入的自增主键值,避免多线程并发插入时Max(Id)取到其他线程插入ID的问题:
public int GetLastInsertedId() { // last_insert_rowid默认返回long类型,确认你的ID范围不会超过int最大值可直接强转 return (int)conn.ExecuteScalar<long>("SELECT last_insert_rowid()"); }
方案3:继续使用Query方法的兼容写法
如果一定要用Query<T>,可以给聚合列加别名,配合极简映射类接收结果:
// 定义通用聚合结果映射类 public class AggregateResult<T> { public T Result { get; set; } } public int GetLastInsertedId() { return conn.Query<AggregateResult<int>>($"SELECT Max(Id) AS Result FROM {typeof(T).Name}").First().Result; }
内容的提问来源于stack exchange,提问作者MisterZeeba
相关产品推荐
相关产品推荐

