C Implementation of DataTable Mapping to Model Method of with source code

  • 2021-09-05 00:40:03
  • OfStack

This paper illustrates the method of C # to map DataTable to Model. Share it for your reference, as follows:

This is a common problem in database development. Of course, this can be solved by the ready-made ORM framework, but sometimes, if DataSet/DataTable is returned by the third-party interface, ORM is inconvenient and has to be handled by itself.

Reflection is naturally necessary. In addition, considering that ColumnName in DataTable usually does not correspond strictly to PropertyName in Model, Attribute can be used to record this mapping relationship.

Step 1: Create an DataFieldAttribute class first


using System;
namespace Jimmy.ORM
{
 [AttributeUsage(AttributeTargets.Property)]
 public sealed class DataFieldAttribute:Attribute
 {
 /// <summary>
 ///  The field name corresponding to the table 
 /// </summary>
 public string ColumnName { set; get; }
 public DataFieldAttribute(string columnName)
 {
  ColumnName = columnName;
 }
 }
}

Step 2: Apply the DataField feature on the Class member of Model/Entity, see the following code:


using System;
namespace Jimmy.ORM.Entity
{
 [Serializable]
 public class ProductEntity : DataEntityBase
 {
 [DataField("PRODUCT_NO")]
 public string ProductNo { set; get; }
 [DataField("PRODUCT_ID")]
 public int ProductId { set; get; }
 [DataField("PRODUCT_NAME")]
 public string ProductName { set; get; }
 public override string ToString()
 {
  return string.Format("ProductNo:{1}{0}ProductId:{2}{0}ProductName:{3}", Environment.NewLine, ProductNo,
     ProductId, ProductName);
 }
 }
}

Step 3: The reflection appears, and an DataConvert class is encapsulated for convenience


using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
namespace Jimmy.ORM
{
 /// <summary>
 ///  Will DataRow/DataTable Convert to Entity/Entity List 
 /// </summary>
 public static class DataConvert<T> where T : DataEntityBase, new()
 {
 /// <summary>
 ///  Will DataRow Row conversion to 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)
  {
   // Read the on the property DataField Characteristic 
   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))
    {
    // According to ColumnName , will dr Assign a value to the relative fields in the Entity Attribute 
    propInfo.SetValue(entity,
     Convert.ChangeType(dr[dataFieldAttr.ColumnName], propInfo.PropertyType),
     null);
    }
   }
   }
  }
  }
  return entity;
 }
 /// <summary>
 ///  Will DataTable Convert to Entity List 
 /// </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;
 }
 }
}

Step 4: Test


using System;
using System.Data;
using Jimmy.ORM.Entity;
namespace Jimmy.ORM.Test
{
 class Program
 {
 static void Main()
 {
  DataTable dt = new DataTable();
  dt.Columns.Add("PRODUCT_NO");
  dt.Columns.Add("PRODUCT_ID");
  dt.Columns.Add("PRODUCT_NAME");
  dt.Rows.Add("00001", 1, " Mobile phone ");
  dt.Rows.Add("00002", 2, " Clothing ");
  var products = DataConvert<ProductEntity>.ToList(dt);
  foreach (var entity in products)
  {
  Console.WriteLine(entity);
  }
  Console.Read();
 }
 }
}

Complete example code code click here to download this site.

I hope this article is helpful to everyone's C # programming.


Related articles: