Convert rows from a data reader into typed results

后端 未结 10 2292
醉梦人生
醉梦人生 2020-11-27 11:53

I\'m using a third party library which returns a data reader. I would like a simple way and as generic as possible to convert it into a List of objects.
For example, say

10条回答
  •  无人及你
    2020-11-27 12:22

    Do you really need a list, or would IEnumerable be good enough?

    I know you want it to be generic, but a much more common pattern is to have a static Factory method on the target object type that accepts a datarow (or IDataRecord). That would look something like this:

    public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
    
        public static Employee Create(IDataRecord record)
        {
            return new Employee
            {
               Id = record["id"],
               Name = record["name"]
            };
        }
    }
    

    .

    public IEnumerable GetEmployees()
    {
        using (var reader = YourLibraryFunction())
        {
           while (reader.Read())
           {
               yield return Employee.Create(reader);
           }
        }
    }
    

    Then if you really need a list rather than an IEnumerable you can call .ToList() on the results. I suppose you could also use generics + a delegate to make the code for this pattern more re-usable as well.

    Update: I saw this again today and felt like writing the generic code:

    public IEnumerable GetData(IDataReader reader, Func BuildObject)
    {
        try
        {
            while (reader.Read())
            {
                yield return BuildObject(reader);
            }
        }
        finally
        {
             reader.Dispose();
        }
    }
    
    //call it like this:
    var result = GetData(YourLibraryFunction(), Employee.Create);
    

提交回复
热议问题