c# - 从单个字符串列请求 1..N 值时,QueryAsync() 返回什么?

标签 c# sqlite linq-to-sql async-await return-type

使用此代码(有或没有“.ToList()”):

public async Task<List<String>> SelectDistinctGroupNames()
{
    var db = new SQLiteAsyncConnection(SQLitePath);
    var groupNames = await db.QueryAsync<List<string>>("SELECT DISTINCT GroupName FROM SOs_Locations");
    return groupNames.ToList();
}

...我明白了,“无法将类型‘System.Collections.Generic.List>’隐式转换为‘System.Collections.Generic.List’

这个有效:

public async Task<HashSet<String>> SelectDistinctGroupNames()
{
    var db = new SQLiteAsyncConnection(SQLitePath);
    var allLocations = await db.QueryAsync<SOs_Locations>("SELECT * FROM SOs_Locations ORDER BY GroupName");
    HashSet<string> hashsetGroupNames = null;
    foreach (var item in allLocations)
    {
        hashsetGroupNames.Add(item.GroupName);
    }
    return hashsetGroupNames;
}

...但似乎很浪费(抓取所有记录,而我想要的只是来自 GroupName 列的不同值)。

在我看来,当用“DISTINCT GroupName”替换 sql 查询中的“*”时,需要的是一个 List 甚至是一个 HashSet

那么当返回来自多个记录的单个列时,究竟返回了什么? IOW,调用 QueryAsync<>() 的尖括号内应该包含什么?

我认为这可行:

public async Task<List<String>> SelectDistinctGroupNames()
{
    var db = new SQLiteAsyncConnection(SQLitePath);
    List<string> allLocations = await db.QueryAsync<string>("SELECT DISTINCT GroupName FROM SOs_Locations ORDER BY GroupName");
    return allLocations;
}

...但是我得到,“‘string’必须是具有公共(public)无参数构造函数的非抽象类型,以便将其用作泛型类型或方法‘SQLite’中的参数‘T’。 SQLiteAsyncConnection.QueryAsync(string, params object[])'"

我上面有一个“字符串”对应于<SOs_Locations >(不是“List <SOs_Locations >”)在该方法的工作版本中。当我将其更改为“List <string >”时,我得到“无法将类型‘System.Collections.Generic.List <System.Collections.Generic.List’隐式转换为‘System.Collections.Generic.List <string >’”

最佳答案

来自 the source :

public Task<List<T>> QueryAsync<T> (string sql, params object[] args)
        where T : new ()

所以如果你想要List<string>因此,您需要通过 string对于 T .如您所见,string无法满足 new()约束(因为它没有无参数构造函数),所以这是不可能的。

我看了一下代码,在我看来它像 new()约束是不必要的,所以我的第一站是 sqlite-net 人员要求他们删除它(并验证 T=string 是否有效)。

同时,您应该能够为这个查询的结果创建一个类型:

public sealed class DistinctGroupNamesResult
{
  public string GroupName { get; set; }
}

并使用一个简短的转换:

public async Task<List<String>> SelectDistinctGroupNames()
{
  var db = new SQLiteAsyncConnection(SQLitePath);
  var result = await db.QueryAsync<DistinctGroupNamesResult>("SELECT DISTINCT GroupName FROM SOs_Locations");
  return result.Select(x => x.GroupName).ToList();
}

可能有更简单的解决方案,例如,使用更高级别的 LINQ 提供程序(但不确定它是否支持 DISTINCT )。或者可以使用 SOs_Locations作为结果类型而不是 DistinctGroupNamesResult .

关于c# - 从单个字符串列请求 1..N 值时,QueryAsync() 返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13792645/

相关文章:

c# - 我的数据库连接关闭了吗? (Linq to Sql)

c++ - 如何使用 C++ 将 sqlite 数据库中的所有表从一个数据库复制到另一个数据库

c# - ListBox 插入颜色项目

c# - 将控件插入 Tab 键顺序的最佳方法?

c# - 如何通过图形 API 将带有地点(位置)的帖子添加到用户的墙上?

node.js - Sequelize object.add 不返回 id?

c - C.sqlite3_exec : parameter set in callback function prints incomplete data when called in main() 中的 SQLite

c# - 选择对象的子子项

Linq 到 SQL SP 参数

c# - 主题页面错误中的 ELMAH