2

对于此示例,我定义了以下类,该类保存在 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 DB 中选择数据。

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 选择时,不会选择任何结果。

我知道具有给定 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。

知道为什么会发生这种情况吗?

4

1 回答 1

1

我认为您的问题可能与您班级的 AutoIncrement 属性有关。尝试删除 AutoIncrement 属性,看看是否可以通过 id 找到图像。

我认为正在发生的事情是 AutoIncrement 属性正在设置 Id,覆盖您创建的 id。

例如

假设您使用以下命令创建 MyImage 的实例:

MyImage i = new MyImage() { Id= 5 , ImageName="imageName"}

当您运行 CurrentConnection.InsertAsync(i) (在空表上)时,插入到数据库中的条目的 ID 为1,而不是5

希望有帮助

于 2012-12-14T19:13:34.953 回答