数据行提取到C#对象 [英] fetch datarow to c# object

查看:114
本文介绍了数据行提取到C#对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类项目的重新$ P $列表中psents的项目。我在调用存储过程返回的数据表功能它,我需要将数据表转换为项目的数组。
这是我做的:

I have an class Item that represents an item in a list. I have in it function that calls stored procedure that returns datatable and I need to convert the datatable to Array of items. Here is what I do:

public class Item
{
    private string _ItemIdDataName = "item_id";
    private string _ItemNameDataName = "item_name";
    private string _PriceDataName = "price";

    public long ItemId { get; set; }
    public string ItemName { get; set; }
    public float Price { get; set; }

    private Item(DataRow row)
    {
        if (row != null)
        {
            ItemId = long.Parse(row[_ItemIdDataName].ToString());
            ItemName = row[_ItemNameDataName].ToString();
            Price = float.Parse(row[_PriceDataName].ToString());
        }
    }

    public Item[] load()
    {
        DataTable dt=DBHandler.GetItems();//Stored procedure that returns DataTable 
        Item[] items = new Item[dt.Rows.Count];
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            items[i] = new Item(dt.Rows[i]);
        }
        return items;
    }
}

我这样做对吗?
我怎样才能提高呢?

Am I doing it right? How can I improve this?

推荐答案

如果你只是要使用它,一旦它可能是好的,但如果你会做了很多,你应该试着做一些更通用的东西。我写了一篇博客文章如何写数据表创建对象的列表的扩展方法。它通过该公约,在对象的属性应该有相同的名称,在存储过程中的列(我想在存储过程中,如果我能改名字):

If you're only gonna use it once it probably fine, but if you'll do it a lot you should try to do some more generic stuff. I wrote a blog post about how to write an extension method for DataTable that creates a list of objects. It works by the convention that the properties in the object should have the same name as the columns in the stored procedure (I would change the name in the stored procedure if I could):

public static class DataTableExtensions
{
    public static IList<T> ToList<T>(this DataTable table) where T : new()
    {
        IList<PropertyInfo> properties = typeof(T).GetProperties().ToList();
        IList<T> result = new List<T>();

        foreach (var row in table.Rows)
        {
            var item = CreateItemFromRow<T>((DataRow)row, properties);
            result.Add(item);
        }

        return result;
    }

    public static IList<T> ToList<T>(this DataTable table, Dictionary<string, string> mappings) where T : new()
    {
        IList<PropertyInfo> properties = typeof(T).GetProperties().ToList();
        IList<T> result = new List<T>();

        foreach (var row in table.Rows)
        {
            var item = CreateItemFromRow<T>((DataRow)row, properties, mappings);
            result.Add(item);
        }

        return result;
    }

    private static T CreateItemFromRow<T>(DataRow row, IList<PropertyInfo> properties) where T : new()
    {
        T item = new T();
        foreach (var property in properties)
        {
            property.SetValue(item, row[property.Name], null);
        }
        return item;
    }

    private static T CreateItemFromRow<T>(DataRow row, IList<PropertyInfo> properties, Dictionary<string, string> mappings) where T : new()
    {
        T item = new T();
        foreach (var property in properties)
        {
            if(mappings.ContainsKey(property.Name))
                property.SetValue(item, row[mappings[property.Name]], null);
        }
        return item;
    }
}

现在,你可以叫

var items = dt.ToList<Item>();

var mappings = new Dictionary<string,string>();
mappings.Add("ItemId", "item_id");
mappings.Add("ItemName ", "item_name");
mappings.Add("Price ", "price);
var items = dt.ToList<Item>(mappings);

这篇博客是在这里:<一href=\"http://blog.tomasjansson.com/2010/11/convert-datatable-to-generic-list-extension\">http://blog.tomasjansson.com/2010/11/convert-datatable-to-generic-list-extension

有许多方式可以扩展这一点,你可能包括某种映射字典告诉分机号来映射列,在这样的名字不需要匹配。或者,你可以添加属性名称的列表,你想在映射排除。

There are many ways in which you can extend this, you could include some kind of mapping dictionary telling the extension how to map the columns, in that way the names doesn't need to match. Or you can add a list of property names that you would like to exclude in the mapping.

更新:您的对象(项目)要创建必须有一个默认的构造函数,否则私有方法将无法创建它。由于该解决方案的工作方式是先创建对象比使用你的属性从反射来设置对象的值。

Update: Your object (Item) you are creating must have a default constructor otherwise the private method won't be able to create it. Since the way the solution works is first to create the object than use the properties that you get from the reflection to set the values of the object.

更新2:我增加了部分与映射字典,而是还没有尝试过自己,所以它可能无法进行编译。然而,这个概念是存在的,我觉得它的工作原理。

Update 2: I added the part with mappings dictionary but haven't tried it myself so it might not compile. However, the concept is there and I think it works.

这篇关于数据行提取到C#对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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