如何选择数据导入列表< T>而不是数据表? [英] How to select data into List<T> instead of DataTable?

查看:98
本文介绍了如何选择数据导入列表< T>而不是数据表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是如何我目前正在从数据库中选择数据:

This is how currently I'm selecting data from database:

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,我想选择列表,而不是数据表。像这样的:

But it return DataTable and I want to select List instead of DataTable. Like this:

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];
}



我怎样才能做到这一点?

How can I do this?

感谢

推荐答案

我建议你使用的短小精悍点网的,如果你不想钻进去的LINQ to SQL或实体框架。自己周围摸索与的IDataReader 来兑现你的结果是不值得在大多数情况下的功夫。

I'd recommend you to use dapper-dot-net, if you do not want to dig into LINQ to SQL or Entity Framework. Fumbling around yourself with IDataReader to materialise your result isn't worth the effort in most cases.

这篇关于如何选择数据导入列表&LT; T&GT;而不是数据表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆