How to convert DataSet to Entity in C#?
Asked Answered
J

2

5

Here I came up with the first approach: that is, using foreach clause on DataSet to get the items and fill in your Entity. But this method can't be reused when the something changes.

So I think maybe reflection should be the best approach for my scenario. below are the details:

1.My entity is defined below:

using System.ComponentModel;

namespace WarningServiceForYM.Model
{
   public class StuffEntity
   {
    [Description("企业ID")]
    public string EnterpriseID { get; set; }  

     [Description("冰柜编号")]
    public string FridgeID { get; set; }        

    [Description("冰柜名称")]
    public string FridgeName { get; set; }   

    [Description("手机号码")]
    public string PhoneNumber { get; set; }  

    [Description("设备名称")]
    public string EquipmentName { get; set; } 

    [Description("采集参数")]
    public string PickingParams { get; set; }   

    [Description("一路温度")]
    public string TempOne { get; set; }         

    [Description("二路温度")]
    public string TempTwo { get; set; }         

    [Description("三路温度")]
    public string TempThree { get; set; }         

    [Description("四路温度")]
    public string TempFour { get; set; }         

    [Description("五路温度")]
    public string TempFive { get; set; }         

    [Description("六路温度")]
    public string TempSix { get; set; }         

    [Description("七路温度")]
    public string TempSeven { get; set; }         

    [Description("八路温度")]
    public string TempEight { get; set; }         

    [Description("温度最低")]
    public string  Min { get; set; }    

    [Description("温度最高")]
    public string Max { get; set; }  

    [Description("采集时间")]
    public string PickingTime { get; set; } 

    [Description("通知间隔")]
    public string WarningPeriod { get; set; }  

    [Description("延时")]
    public string PendingTime { get; set; }  

    [Description("通知开关")]
    public string Switch { get; set; }  

    [Description("最后通知时间")]
    public string LastInformTime { get; set; }  
    }
}
  1. Below is the DataSet screenshot: enter image description here

I have saved this DataSet's data into csv file, pls click here to find it.

the inner properties in the StuffEntity have the same Description as the column headers in DataSet.

Would any one give me a method to show how to convert this Dataset to StuffEntity ? thx.

Jochbed answered 10/10, 2013 at 2:50 Comment(4)
I wonder if you can use Entity Framework instead of doing it manually. Since the data comes from the database, it would be very straightforward to update your model using EF. Otherwise the reflection approach must solve. Is your dataset complex like having more than one datatable or having relationships?Sensitize
Using reflection, your question looks like a duplicate of this and thisSensitize
@Sensitize only one table in the DataSet. I saw the link you give, but it's not a generic solution. is there any possible to write the convert method once but use in other places? is there a possibility to reflect property description to convert?Jochbed
@Sensitize it's a small widget in my porject in charge of message sending. EF is too heavy for me. thx.Jochbed
S
8

Ok, using reflection:

public static T GetEntity<T>(DataRow row) where T : new()
{
    var entity = new T();
    var properties = typeof(T).GetProperties();

    foreach (var property in properties)
    {
        //Get the description attribute
        var descriptionAttribute = (DescriptionAttribute)property.GetCustomAttributes(typeof(DescriptionAttribute), true).SingleOrDefault();
        if (descriptionAttribute == null)
            continue;

        property.SetValue(entity, row[descriptionAttribute.Description]);
    }

    return entity;
}

You can use it like:

foreach (DataRow dataRow in dataSet.Tables[0].Rows)
{
    var e = GetEntity<StuffEntity>(dataRow);
    Console.WriteLine(e.EnterpriseID);
}

It's a generic implementation, so you can use it with any other types or datasets you want. I took care to made it as simple as possible, so it can be widely improved adding some consistences, like checking if the column name exists before setting the entity value or verifying duplicate descriptions as needed. It can also be converted to an extension method for the DataRow, DataTable or DataSet, for example.

Sensitize answered 11/10, 2013 at 1:7 Comment(0)
C
0

I my case Your code almost worked, but descriptionAttribute is always null so it continues to the point where I get no results back

var descriptionAttribute = (DescriptionAttribute)property.GetCustomAttributes(typeof(DescriptionAttribute), true).SingleOrDefault();
                if (descriptionAttribute == null)
                    continue;

I am not sure what is happening to the variable descriptionAttribute and it is null all the time.

So I changed @natenho code like this and it worked for me.

 public static T GetEntity<T>(DataRow row) where T : new()
        {
            var entity = new T();
            var properties = typeof(T).GetProperties();

            foreach (var property in properties)
            {
                //Get the description attribute
                //var descriptionAttribute = (DescriptionAttribute)property.GetCustomAttributes(typeof(DescriptionAttribute), true).SingleOrDefault();
                //if (descriptionAttribute == null)
                //    continue;

                if (row[property.Name].ToString() != "")
                {
                    property.SetValue(entity, row[property.Name]);
                }

            }

            return entity;
        }
Caiman answered 18/1, 2023 at 12:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.