1. 背景介绍:
项目的结构是一个PCL可移植, 一个Android的工程:
SQLite数据库对象文件都放在PCL(可移植的)项目中, 但是具体操作数据库部分的逻辑放在.Android项目中.
使用的SQLite.cs 来源https://github.com/praeclarum/sqlite-net
2. 存在的问题:
查询, 插入数据都正常, 但是在进行Update和Delete时, 提示: Cannot update XXX: it has no PK
3. 问题查找
跟踪SQLite.cs源码, 发现下面的代码在判断是否有PK时, 访问不到对象属性, 导致无法正确的识别主键.
(如果数据库对象文件与SQLite.cs都在.Android工程中, 则不会有这个问题)
public static bool IsPK (MemberInfo p){
return p.CustomAttributes.Any (x => x.AttributeType == typeof (PrimaryKeyAttribute));
}
4. 解决方法
由于时间比较紧...没办法查找完美解决方法, 所以这里就治标不治本的方法如下:
public static bool IsPK (MemberInfo p)
{
//-- 当数据库对象文件在可移植类库 (PCL)中时, 该方法无法正确的识别对象的属性类型, 导致Update, Delete操作失败
//-- 所以, 这里将对象中的Id, userid字段, 认为是主键
//return p.CustomAttributes.Any (x => x.AttributeType == typeof (PrimaryKeyAttribute));
bool bPK = p.CustomAttributes.Any(x => x.AttributeType == typeof(PrimaryKeyAttribute));
if (!bPK)
bPK = string.Compare(p.Name, Orm.ImplicitPkName, StringComparison.OrdinalIgnoreCase) == 0;
if (!bPK)
bPK = string.Compare(p.Name, "userid", StringComparison.OrdinalIgnoreCase) == 0;
return bPK;
}