简体   繁体   English

从数据表数据 C# 创建对象

[英]Create Objects from Datatable data C#

I am creating a Web service that takes to input parameters and returns data in objects.我正在创建一个 Web 服务,它需要输入参数并返回对象中的数据。 I have created a class Sending which has many properties.我创建了一个具有许多属性的类 Sending。

I am retrieving the data from a database and loading them into a datatable.我正在从数据库中检索数据并将它们加载到数据表中。 I am using datatables because i there can be many rows and i need to create an object of the sending class for each row.我正在使用数据表,因为我可以有很多行,我需要为每一行创建一个发送类的对象。

I have also created get and set properties for each variable in the sending class.我还为发送类中的每个变量创建了 get 和 set 属性。

Is there any way to insert the data from the datatable into the class objects?有没有办法将数据表中的数据插入到类对象中?

If you have already created matching datamodel, then you can do something like this如果您已经创建了匹配的数据模型,那么您可以执行以下操作

IList<YourClass> items = yourdatatable.AsEnumerable().Select(x => 
    new YourClass
        {
            field1 = x.Field<int>("idcolumnName"),
            field2 = x.Field<string>("otherColumn")
        }).ToList();

Try this sample Extension.试试这个示例扩展。 improve it with your requirement.根据您的要求改进它。

public static IEnumerable<T> ToIEnumerable<T>(this DataTable dt)
{
    List<T> list = Activator.CreateInstance<List<T>>();
    T instance = Activator.CreateInstance<T>();
    var prop = instance.GetType().GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance);
    foreach (DataRow dr in dt.Rows)
    {
        T ins = Activator.CreateInstance<T>();
        foreach (var p in prop)
        {
            try
            {
                p.SetValue(ins, dr[p.Name], null);
            }
            catch { }
        }
        list.Add(ins);
    }
    return list;
}

usage:用法:

yourDataTable.ToIEnumerable<YourClassModel>();

Don't try to do this by hand.不要尝试手动执行此操作。 ORMs do exactly this job in a much easier way. ORM 以更简单的方式完成这项工作。 You can actually use a Micro-ORM like Dapper.NET or Massive to load data from the database as objects with a minimum of configuration.您实际上可以使用像Dapper.NETMassive这样的 Micro-ORM 以最少的配置从数据库加载数据作为对象。

For example, this query Dapper.NET query will load all Dog objects with the specified age:例如,此查询 Dapper.NET 查询将加载具有指定年龄的所有 Dog 对象:

public class Dog
{
    public int? Age { get; set; }
    ...
}            

var dogs = connection.Query<Dog>("select Age = @Age", new { Age = 5 });

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

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