【问题标题】:SQL ERROR System.Collections.Generic.List`1[Dapper.SqlMapper+DapperRow]SQL 错误 System.Collections.Generic.List`1[Dapper.SqlMapper+DapperRow]
【发布时间】:2020-02-18 22:34:52
【问题描述】:

我希望我的代码返回一个值,但它返回了我:

System.Collections.Generic.List`1[Dapper.SqlMapper+DapperRow]

我无法解决并做出正确的输出过程。

public static string Test()
{
    using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
    {
        var vartest = cnn.Query("select grado from utenti where id='10'");
        //var result = output.ToDictionary(row => (string)row.Grado, row => (string)row.Nome ) ; (commento)
        //Console.WriteLine(vartest);

        cnn.Close();
        return vartest.ToString();
    }
}

【问题讨论】:

  • 这不是错误,这是vartest.ToString()的输出。

标签: c# sqlconnection


【解决方案1】:

QueryQuery<T> 返回多行; Query 用于 dynamic 行; Query<T> 用于键入的行。单行有QueryFirst[<T>]QuerySingle[<T>]

如果您追求的是已知类型的单个值,那么可能:

var vartest = cnn.QuerySingle<string>("select grado from utenti where id='10'");

【讨论】:

    【解决方案2】:

    如果你的意思是你的回报 vartest.ToString();正在返回字符串 "System.Collections.Generic.List`1[Dapper.SqlMapper+DapperRow]" 这是因为您的 vartest 是一个项目列表,您需要 .ToString 列表中的项目

    public static string ManagerFindid() 
    { 
    using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString())) 
        { 
            var select = cnn.Query("select id from utenti"); 
            if (select.Any()) 
            { 
                return select[0].ToString();
                // or do something with all the items in your list               
                foreach(string value in select)
                {
                     //add value into list view
                }
            } 
            else 
            {
                //this is hit when there are no items returned from the select query 
                return "Nothing Returned from Query";
            } 
    } 
    

    您还可以处理从 SQL 返回的多个项目

    foreach(string value in select)
    {
        //do something with current value
    }
    

    【讨论】:

    • 所以如果我想在列表视图中添加更多数据,我应该如何进行? public static string ManagerFindid() { using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString())) { var select = cnn.Query("select id from utenti"); if (select.Any()) { return select[0].ToString(); } 否则返回 select.ToString(); } }
    • 你不想返回'select.ToString();'相反,您应该返回返回列表中没有任何内容。 else { return "查询没有返回任何内容" }
    • 查询 "select id from utenti" 将返回 utenti 表中的所有 Id 值,因此如果您想将此数据添加到列表视图中,您应该遍历从选择返回的字符串列表声明并将每一个添加到列表视图中
    • 我已经更新了我的答案以更详细地显示代码
    • 有了这个我有两个我无法理解的问题。第一个是因为字符串不能是动态值,它给了我这个错误:Error CS0029 不可能将类型'System.Collections.Generic.IEnumerable '隐式转换为'string'我>
    猜你喜欢
    • 2019-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-24
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多