在这里,我想出了第一种方法:即使用DataSet上的foreach子句获取项目并填写您的Entity。但是,当某些事情发生变化时,该方法将无法重用。
因此,我认为反思可能是我的最佳方案。以下是详细信息:
1.我的实体定义如下:
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; }
}
}
我已将此DataSet的数据保存到csv文件中,请单击此处查找它。
StuffEntity中的内部属性与DataSet中的列标题具有相同的描述。
有人可以给我一种方法来显示如何将此数据集转换为StuffEntity吗?
好的,使用反射:
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;
}
您可以像这样使用它:
foreach (DataRow dataRow in dataSet.Tables[0].Rows)
{
var e = GetEntity<StuffEntity>(dataRow);
Console.WriteLine(e.EnterpriseID);
}
这是一个通用的实现,因此您可以将其与所需的任何其他类型或数据集一起使用。我努力使它尽可能简单,因此可以通过添加一些一致性来进行广泛改进,例如在设置实体值之前检查列名是否存在,或者根据需要验证重复的描述。例如,也可以将其转换为DataRow,DataTable或DataSet的扩展方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句