資料庫實體轉換的過程詳解
阿新 • • 發佈:2018-11-22
如何應用反射設定實體的值
首先需要建立實體的例項
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; }
}