简体   繁体   English

如何将 SqlDataReader 结果转换为通用列表 List<T>

[英]How to convert SqlDataReader result to generic list List<T>

I'm trying to fetch records form Azure database using Ado.net I used SqlDataReader class for that.我正在尝试使用 Ado.net 从 Azure 数据库中获取记录,为此我使用了SqlDataReader类。 Even though the data fetch is successful, I don't know how to convert it into a generic list.即使数据获取成功,我也不知道如何将其转换为通用列表。

protected List<T> GetList<T>()
        {
            try
            {
                using (var query = ExecuteReader())
                {
                         // What Goes Here ?
                }

            }
            finally
            {
                if (_sqlCommand.Connection.State == ConnectionState.Open)
                {
                    _sqlCommand.Connection.Close();
                }
            }
        }

ExecuteReader method, ExecuteReader 方法,

protected SqlDataReader ExecuteReader()
        {
            if (_sqlCommand.Connection.State != ConnectionState.Open)
            {
                _sqlCommand.Connection.Open();
            }

            return _sqlCommand.ExecuteReader();
        }

The Data Model,数据模型,

public class Student
    {
        [EntityKey]
        public int StudentId { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public string Major { get; set; }

    }

NOTE : I would like to know if there any other easy ways as well注意:我想知道是否还有其他简单的方法

SqlDataReader isn't a container, it's a cursor used to load data. SqlDataReader 不是容器,它是用于加载数据的游标。 It can't be converted to any container type.它不能转换为任何容器类型。 The application code must use it to load the results and then construct the objects and place them in a list.应用程序代码必须使用它来加载结果,然后构造对象并将它们放在一个列表中。 This is described in the ADO.NET docs, eg in Retrieving data using a DataReader :这在 ADO.NET 文档中有所描述,例如在使用 DataReader 检索数据中

    var list=new List<Student>();
    if (reader.HasRows)
    {
        while (reader.Read())
        {
            var student=new Student();
            student.Id=reader.GetInt32(0);
            student.Name = reader.GetString(1));
            ...
        }
    }
    else
    {
        Console.WriteLine("No rows found.");
    }

That's a lot of boilerplate, which is why ORMs like Entity Framework or micro-ORMs like Dapper are used to execute queries and map the results to objects.这是很多样板,这就是为什么使用像实体框架这样的 ORM 或像Dapper这样的微 ORM 来执行查询并将结果映射到对象的原因。

Using Dapper, all this code can be replaced with :使用 Dapper,所有这些代码都可以替换为:

var sql="Select * from Students where Major=@major";
var students=connection.Query<Student>(sql,new {major="Computer Science"});

Dapper will create a parameterized query with the @major parameter, execute it, construct Student objects from the results and return them as an IEnumerable<Student> . Dapper 将使用@major参数创建一个参数化查询,执行它,从结果构造Student对象并将它们作为IEnumerable<Student>返回。 It even takes care of opening and disposing the connection.它甚至负责打开和处理连接。

Dapper works by using Reflection to identify a type's properties, use their names to load the correct fields and assign them to the objects it creates. Dapper 通过使用反射来识别类型的属性,使用它们的名称来加载正确的字段并将它们分配给它创建的对象。

while (query.Read())
{
  Console.WriteLine($"First column {query[0]}");
  Console.WriteLine($"Named column {query["put a columnname here"]}");
}

Read() will give you the first and next rows. Read() 将为您提供第一行和下一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM