加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何选择数据到List而不是DataTable?

发布时间:2020-12-15 18:20:00 所属栏目:百科 来源:网络整理
导读:这就是我目前从数据库中选择数据的方式: public DataTable GetData(){ DataTable table = new DataTable("Table"); using (SqlConnection connection = new SqlConnection("Connection string")) { SqlCommand command = new SqlCommand(); command.Connect
这就是我目前从数据库中选择数据的方式:
public DataTable GetData()
{
    DataTable table = new DataTable("Table");
    using (SqlConnection connection = new SqlConnection("Connection string"))
    {
        SqlCommand command = new SqlCommand();
        command.Connection = connection;
        command.CommandType = System.Data.CommandType.Text;
        command.CommandText = "query string";

        connection.Open();
        SqlDataAdapter adapter = new SqlDataAdapter(command);
        adapter.Fill(table);
    }
    return table;
}

但它返回DataTable,我想选择List而不是DataTable.像这样:

public List<MyClass> GetData()
{
    DataTable table = new DataTable("Table");
    using (SqlConnection connection = new SqlConnection("Connection string"))
    {
        SqlCommand command = new SqlCommand();
        command.Connection = connection;
        command.CommandType = System.Data.CommandType.Text;
        command.CommandText = "query string";

        connection.Open();
        SqlDataAdapter adapter = new SqlDataAdapter(command);
        adapter.Fill(table);
    }
    ...
    return [List of MyClass];
}

我怎样才能做到这一点?

谢谢!

解决方法

如果您不想深入了解LINQ to SQL或Entity Framework,我建议您使用 dapper-dot-net.在大多数情况下,使用IDataReader在你身边摸索以实现你的结果是不值得的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读