数据库实体转换的过程详解

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_41556165/article/details/84327904

如何应用反射设置实体的值

首先需要创建实体的实例

public class ConfigEntity
    {
        public string ConnectionStr { get; set; }
        public string Name{ get; set; }
        public string Age { get; set; }
    }

然后设置过程如下

ConfigEntity ce = new ConfigEntity();
Type type = typeof(ConfigEntity);
//或者 Type type = ce.GetType();
PropertyInfo[] pis = type.GetProperties();
//GetProperties(BindingFlags.Public);只获取为public的属性
foreach(PropertyInfo pi in pis){
	Object value = Convert.ChangeType(pi.Name,pi.PropertyType);
	pi.SetValue(ce,value,null);
}

也可以不new一个实体,使用target替代ce:

ConfigEntity ce = Activator.CreateInstance<ConfigEntity>();
即:
T target = Activator.CreateInstance<T>();

将DataSet转换为实体

public static List<T> ToEntity<T>(DataSet ds) where T : class
{
    if (ds == null || ds.Tables == null)
        return new List<T>();
    return ToEntity<T>(ds.Tables[0]);
}

将DataTable转换为实体

public static List<T> ToEntity<T>(DataTable dt) where T : class
{
	if(dt == null || dt.Rows.Count < 1){
		return new List<T>();
	}
	List<T> target = new List<T>();
	int rowCount = dt.Rows.Count;
	T item;
	for(int i=0;i<rowCount;i++){
		item = ToEntity<T>(dt.Rows[i]);
		target.Add(item);
	}
	return target;
}

将DataRow转换为实体

public static List<T> ToEntity<T>(DataRow dr)where T : class
{
	T target = Activator.CreatInstance<T>();

	DataColumnCollection dcc = dr.Table.Columns;
	Type type = typeof(T);
	PropertyInfo[] pis = type.GetProperties();
	string columnName = string.Empty;
	foreach(PropertyInfo pi in pis)
	{
		IgnoreAttribute ignoreAttr = Attribute.GetCustomAttribute(pi, typeof(IgnoreAttribute)) as IgnoreAttribute;
      if (ignoreAttr != null)
            continue;
      ColumnAttribute attr = Attribute.GetCustomAttribute(pi, typeof(ColumnAttribute)) as ColumnAttribute;
      if (attr != null)
      {
          columnName = attr.ColumnName;
      }
      else
       {
           columnName = pi.Name;
       }
       if (dcc.Contains(columnName))
       {
           pi.SetValue(target, ChangeType(dr[columnName], pi.PropertyType), null);
       }		
	}
	return target;
}

自定义属性

[AttributeUsage(AttributeTargets.Property,Inherited=false,AllowMultiple=false)]
public class IgnoreAttribute:Attribute
{
}

[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
    public class ColumnAttribute : Attribute
    {
        // See the attribute guidelines at 
        //  http://go.microsoft.com/fwlink/?LinkId=85236

        // This is a positional argument
        public ColumnAttribute(string columnName = "")
        {
            this.ColumnName = columnName;
        }

        public string ColumnName { get; set; }
    }

猜你喜欢

转载自blog.csdn.net/weixin_41556165/article/details/84327904
今日推荐