In the actual development process, or the data table structure provided by a third-party company does not correspond to the entity class fields in our system, how should we deal with this? Some people may say that it is not enough to create an entity object during conversion and traverse the data in the table row by row to instantiate the entity object. Yes, this method is feasible, but this method is extremely inefficient. If you encounter hundreds of millions of data, you will have to instantiate hundreds of millions of objects, which shows its efficiency.
Let’s take a look at my entity class first
/// <summary> /// 具体的实体类,和数据表中不同 /// </summary> public class Person { [DataField("user_name")]//表示数据库表里面的字段 public string UserName { set; get; }//表示需要转换成的字段 [DataField("pass_word")] public string PassWord { set; get; } }
There are comments in the code specifically. The following is the conversion class
[AttributeUsage(AttributeTargets.Property)] public sealed class DataFieldAttribute : Attribute { /// <summary> /// 表对应的字段名 /// </summary> public string ColumnName { set; get; } public DataFieldAttribute(string columnName) { ColumnName = columnName; } } public static class DataConvert<T> where T : new() { /// <summary> /// 将DataRow行转换成Entity /// </summary> /// <param name="dr"></param> /// <returns></returns> public static T ToEntity(DataRow dr) { T entity = new T(); Type info = typeof(T); var members = info.GetMembers(); foreach (var mi in members) { if (mi.MemberType == MemberTypes.Property) { //读取属性上的DataField特性 object[] attributes = mi.GetCustomAttributes(typeof(DataFieldAttribute), true); foreach (var attr in attributes) { var dataFieldAttr = attr as DataFieldAttribute; if (dataFieldAttr != null) { var propInfo = info.GetProperty(mi.Name); if (dr.Table.Columns.Contains(dataFieldAttr.ColumnName)) { //根据ColumnName,将dr中的相对字段赋值给Entity属性 propInfo.SetValue(entity, Convert.ChangeType(dr[dataFieldAttr.ColumnName], propInfo.PropertyType), null); } } } } } return entity; } /// <summary> /// 将DataTable转换成Entity列表 /// </summary> /// <param name="dt"></param> /// <returns></returns> public static List<T> ToList(DataTable dt) { List<T> list = new List<T>(dt.Rows.Count); foreach (DataRow dr in dt.Rows) { list.Add(ToEntity(dr)); } return list; } }
Calling code:
DataTable dt = new DataTable(); dt.Columns.Add("user_name"); dt.Columns.Add("pass_word");//这是表中的字段,现在需要将它们转换为具体的实体类实例 dt.Rows.Add("kingtiger","1"); dt.Rows.Add("wangbiao", "2"); var users = DataConvert<Person>.ToList(dt); foreach (var user in users) { Response.Write(user.UserName + "," + user.PassWord); } for (int i = 0; i < dt.Rows.Count; i++) { Person p = DataConvert<Person>.ToEntity(dt.Rows[i]); Response.Write(p.UserName + "," + p.PassWord); }
More c# DataTable and For articles related to method examples for converting different structural entity classes, please pay attention to the PHP Chinese website!