【发布时间】:2021-08-29 07:33:28
【问题描述】:
- 我希望 queryOutput 能够实现?
- 为什么 当 fieldcount 已经有 IEnumerable 时,是否尝试调用 fieldcount 无效?
/// <summary>
/// Get all columns for a certain table
/// </summary>
public async Task<List<Tuple<string, string, int?>>> GetAllColumnsFromTableAsync(string tableName)
{
List<Tuple<string, string, int?>> result;
string query = "SELECT COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME= @tableName";
using (IDbConnection db = DbConnection)
{
IEnumerable<Tuple<string, string, int?>> queryOutput = await db.QueryAsync<string, string, int?, Tuple<string, string, int?>>
(query, Tuple.Create, new { tableName = tableName }, null, false, splitOn: "*");
result = queryOutput.ToList(); // System.InvalidOperationException: Invalid attempt to call FieldCount when reader is closed.
}
if (result is not null && result.Count > 0)
{
return result;
}
else
{
return default;
}
}
- 将此作为非异步方法有效。所以它必须是“tuple”+“dapper”+“async”
参考:https://github.com/DapperLib/Dapper/issues/745
更新:
-
当用命名元组替换元组时,查询本身 有效。
public async Task<List<(string COLUMN_NAME, string DATA_TYPE, int? CHARACTER_MAXIMUM_LENGTH)>> GetAllColumnsFromTableAsync2(string tableName) { const string query = "SELECT COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME= @tableName"; using var connection = new SqlConnection(_connectionstring); var output = await connection.QueryAsync<(string COLUMN_NAME, string DATA_TYPE, int? CHARACTER_MAXIMUM_LENGTH)> (query, new { tableName = tableName }); return output.ToList(); }
我还有一个问题,但这是另一个问题。
【问题讨论】:
-
Dapper 文档指出查询结果是 List 实例,因此我通常执行以下操作:
return connection.Query<MyDto>(sql) as IList;` -
退出 using 块前需要等待结果。
-
@john-wu 据我所知,我正在等待“等待”的结果? (并将 {} 放在我添加的 using 周围,以查看这是否会产生影响,因为它们不需要
-
@RoarS。据我所知,我做'tolist'?
-
我的猜测是
DbConnection关闭得太早了。我无法从您的代码中看到它是在哪里创建的。如果您尝试用我的答案中的相同代码替换代码的那部分,那可以验证/伪造。
标签: c# sql-server .net-core dapper