从数据读取器转换成行输入结果 [英] Convert rows from a data reader into typed results

查看:167
本文介绍了从数据读取器转换成行输入结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是第三方库返回数据读取器。我想一个简单的方法,并尽可能地通用将其转换为对象的名单。

例如,假设我有2个属性雇员和名称类雇员,我想数据读取器(其中包含员工列表)转换成列表<员工>

我想我没有选择,只能迭代虽然数据读取器的行和为每个转换成他们一个Employee对象,我会添加到列表中。任何更好的解决方案?我使用C#3.5和理想,我想它是尽可能通用的,所以它适用于任何类(在DataReader的字段名称相匹配的各种对象的属性名称)。

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 I have a class 'Employee' with 2 properties EmployeeId and Name, I would like the data reader (which contains a list of employees) to be converted into List< Employee>.
I guess I have no choice but to iterate though the rows of the data reader and for each of them convert them into an Employee object that I will add to the List. Any better solution? I'm using C# 3.5 and ideally I would like it to be as generic as possible so that it works with any classes (the field names in the DataReader match the property names of the various objects).

推荐答案

你真的需要一个列表,或者将IEnumerable的不够好?

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

我知道你希望它是通用的,但更常见的模式是对目标对象类型,它接受一个数据行(或IDataRecord)静态工厂方法。这将是这个样子:

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<Employee> GetEmployees()
{
    using (var reader = YourLibraryFunction())
    {
       while (reader.Read())
       {
           yield return Employee.Create(reader);
       }
    }
}

如果你的

然后真正的需要一个列表,而不是一个IEnumerable你可以叫 .ToList()的结果。我想你也可以使用泛型+委托来使code为这种模式更可重复使用的为好。

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.

更新:我看到这个今天再次,感觉就像写普通code:

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

public IEnumerable<T> GetData<T>(IDataReader reader, Func<IDataRecord, T> BuildObject)
{
    try
    {
        while (reader.Read())
        {
            yield return BuildObject(reader);
        }
    }
    finally
    {
         reader.Dispose();
    }
}

//call it like this:
var result = GetData(YourLibraryFunction(), Employee.Create);

这篇关于从数据读取器转换成行输入结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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