C implements the method of converting DataSet to Model using generics

  • 2021-07-13 06:04:55
  • OfStack

This article illustrates the C # implementation of converting DataSet to Model using generics. Share it for your reference. The details are as follows:

Because the website needs to be developed with C #, used to java generics, so look at 1 under C #, can also do this, casually write 1.


public static List<T> PutAllVal<T>(T entity, DataSet ds) where T : new() {
  List<T> lists = new List<T>();
  if (ds.Tables[0].Rows.Count > 0) {
    foreach (DataRow row in ds.Tables[0].Rows) {
      lists.Add(PutVal(new T(),row));
    }
  }
  return lists;
}
public static T PutVal<T>(T entity, DataRow row) where T : new() {
  // Initialization   If is null
  if (entity == null){
    entity = new T();
  }
  // Get the type 
  Type type = typeof(T);
  // Get a collection of attributes 
  PropertyInfo[] pi = type.GetProperties();
  foreach (PropertyInfo item in pi){
    // Assign a value to an attribute 
    if (row[item.Name] != null && row[item.Name] != DBNull.Value) {
      if (item.PropertyType == typeof(System.Nullable<System.DateTime>)) {
        item.SetValue(entity, Convert.ToDateTime(row[item.Name].ToString()), null);
      } else {
        item.SetValue(entity, Convert.ChangeType(row[item.Name], item.PropertyType), null);
      }
    }
  }
  return entity;
}

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


Related articles: