【问题标题】:SQL Lite Xamarin : QuerySQLite Xamarin:查询
【发布时间】:2014-10-21 08:12:55
【问题描述】:

我是 SQLite 的新手。

我想查询我的 SQLite 数据库以获取多行。

当我在本地数据库中添加新项目时,我将此方法称为 Add:

public bool Add<T>(string key, T value)
{
    return this.Insert(new SQliteCacheTable(key, this.GetBytes(value))) == 1;
}

_simpleCache.Add("favorite_1", data1);
_simpleCache.Add("favorite_2", data2);
_simpleCache.Add("favorite_3", data2);

那么,

我想从本地数据库中检索键以“favorite_”开头的所有条目 返回数据库中所有“最喜欢”的对象。

我在 Linq 方面经验丰富,我想做这样的事情:

IEnumerable<Element> = repository.Find((element) => element.Key.StartWith("favorite_"))

SQLiteConnection 类中有这样一个方法:

SQLite.Net.SQLiteConnection.Find<T>(System.Linq.Expressions.Expression<System.Func<T,bool>>)

但我希望与 in 返回集合 IEnumerable&lt;T&gt; 相同。

你能帮帮我吗?

谢谢。

乔尔

【问题讨论】:

    标签: sqlite xamarin


    【解决方案1】:

    您必须在表本身而不是连接上构建查询:

    假设:

    SQLiteConnection repository;
    

    那么代码如下所示:

    var favorites = repository.Table<SQliteCacheTable>().Where(item => item.StartsWith("favorite_"));
    

    favorites 变量的类型为 TableQuery&lt;SQliteCacheTable&gt;,因此它还不包含您的数据。实际 SQL 查询的执行将延迟到您尝试访问结果(例如,通过使用 foreach 枚举或使用 ToList 转换为列表)。

    要实际观察数据库上发生的情况,您可以在 sqlite-net 中打开跟踪,方法是在您的 SQLiteConnection 对象上设置 repository.Trace = true

    最后,值得一提的是,您还可以在 TableQuery&lt;T&gt; 对象上使用 C# 查询语法,如果您愿意的话。所以你的查询可能变成:

    var favorites = from item in repository.Table<SQliteCacheTable>()
                    where item.StartsWith("favorite_")
                    select item;
    

    【讨论】:

    • 是的,它运行良好。非常感谢。最后很简单。
    猜你喜欢
    • 1970-01-01
    • 2018-06-15
    • 1970-01-01
    • 2018-11-26
    • 2021-01-13
    • 2023-04-10
    • 2023-03-18
    • 1970-01-01
    • 2021-12-02
    相关资源
    最近更新 更多