对于这个例子,我定义了以下类,它保存在 SQLite 数据库中:
[SQLite.AutoIncrement, SQLite.PrimaryKey, SQLite.Indexed]
public int ID { get; set; }
[SQLite.Indexed]
public string ImageName { get; set; }
我正在使用 sqlite-net 提供的插入命令,它有效:
SQLiteAsyncConnection CurrentConnection = new SQLiteAsyncConnection("DB");
int result = await CurrentConnection.InsertAsync(this);
之后,我尝试从 SQLite 数据库中选择数据。
List<Image> result = new List<Image>();
if (ImageName != null)
{
query = CurrentConnection.Table<Image>().Where(i => i.ImageName == ImageName);
result = await query.ToListAsync();
}
if (ID != null && ID > 0)
{
query = CurrentConnection.Table<Image>().Where(i => i.ID == ID);
result = await query.ToListAsync();
}
if (result.Count > 0)
{
LoadFromResult(result[0]);
return;
}
当按 ImageName 选择时,一切正常,我得到了我需要的结果。但是,当尝试按 ID 选择时,没有选择任何结果。
我知 Prop 有给定 ID 的图像存在,因为我刚刚插入它并随后检查了 ID,但由于某种原因,这不起作用。
我是不是完全瞎了,在这里漏了一个小信?有没有人使用 SQLite-net 尝试通过主键进行选择?
//编辑
也试过这个,没用:
var query1 = await CurrentConnection.QueryAsync<Image>("select * from Image where ID = ?", ID);
if (query1.Count > 0)
{
LoadFromResult(query1[0]);
return;
}
//编辑2
我对此有一些预感 - 当我插入图像时,ID 确实设置为某个 ID,但是当我选择数据库中的所有图像时,它们的 ID 均为 0。
知道为什么会发生这种情况吗?
最佳答案
我认为您的问题可能与您类(class)的 AutoIncrement 属性有关。 尝试删除 AutoIncrement 属性并查看是否可以通过 id 找到图像。
我认为正在发生的事情是 AutoIncrement 属性正在设置 Id,覆盖您创建的 id。
例如
假设您使用以下方法创建 MyImage 的实例:
MyImage i = new MyImage() { Id=5, ImageName="imageName"}
当您运行 CurrentConnection.InsertAsync(i)(在空表上)时,插入到数据库中的条目的 ID 为 1,而不是 5。
希望对您有所帮助
关于c# - 尝试使用 sqlite-net 按 PrimaryKey 选择时,SQLite 没有结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13848966/