Arbitrary/string return 来自 LiteDb 查询的值

Arbitrary/string return value from LiteDb query

我有一个 LiteDb 数据库,我希望用户能够在该数据库上 运行 任意查询(以字符串形式给出;假设我们要求他们的查询也总是 return 一个字符串) .不幸的是,我似乎总是被锁定在接收集合中给出的类型。例如查询

SELECT "hello"
据我所知,

是有效的 SQL,但 LiteDb 不解析它:

new LiteDatabase(dbFile).GetCollection<MyType>().Find("SELECT 'hello'");

报错

Unexpected token HELLO in position 10.

当然,这个例子会失败并不意外,因为 Find 应该总是 return 和 IEnumerable<MyType> 但我找不到可以 运行 任意有效查询。有解决这个问题的好方法吗?我知道 LiteDb 不应该是 SQL 服务器,但我需要这种灵活性以允许用户从他们的逻辑中取回字符串;有点像允许他们对数据库进行一些编程。

您可以在 LiteDatabase 实例中使用 Execute() 方法。它基本上 returns 你 BsonValues 的集合:

var result = liteDatabase.Execute("SELECT 'John' AS Name, 34 AS Age").ToEnumerable()
    .SelectMany(x => ((Dictionary<string, BsonValue>)x.RawValue)
    .ToDictionary(y => y.Key, y => y.Value.RawValue.ToString()));

foreach (var r in result) Console.WriteLine($"{r.Key}: {r.Value}");

但是,这会带来很大的负担,使您有义务考虑所有可能的复杂形式。在这种简单的情况下,您将获得一个 KeyValuePair,但是对于更复杂的查询,您必须处理更复杂的输出 - 因此我建议您限制自己只处理 KeyValuePairs 或类似的数据结构。