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

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

首先需要创建实体的实例

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; }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值