在项目开发中,我用这个方法从数据库读取数据封装实体类,减少体力代码量,犹其是一个类字段特多时。但我不知道这样会有什么问题,请大家指点,共同进步呀。
1.EntityHelper:
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
namespace Tuo.Dao
{
public class EntityHelper
{
public static T GetEntity<T>(DataTable table) where T : new()
{
T entity = new T();
foreach (DataRow row in table.Rows)
{
foreach (var item in entity.GetType().GetProperties())
{
if (row.Table.Columns.Contains(item.Name))
{
if (DBNull.Value != row[item.Name])
{
item.SetValue(entity, row[item.Name].ToString(), null);
}
}
}
}
return entity;
}
public static IList<T> GetEntities<T>(DataTable table) where T : new()
{
IList<T> entities = new List<T>();
foreach (DataRow row in table.Rows)
{
T entity = new T();
foreach (var item in entity.GetType().GetProperties())
{
item.SetValue(entity, row[item.Name].ToString(), null);
}
entities.Add(entity);
}
return entities;
}
public static T ParseEntity<T>(object src) where T : new()
{
T entity = new T();
foreach (var targetPro in typeof(T).GetProperties())
{
foreach (var srcPro in src.GetType().GetProperties())
{
if(targetPro.Name==srcPro.Name){
targetPro.SetValue(entity, src.GetType().GetProperty(srcPro.Name).GetValue(src, null), null);
}
}
}
return entity;
}
/*
public static object ParseEntity(object source, Type target)
{
//object srcObj = Activator.CreateInstance(source);
// Type srcType=
if (source == null)
{
return null;
}
object tarObj = Activator.CreateInstance(target);
try
{
foreach (var src in source.GetType().GetProperties())
{
foreach (var tar in target.GetProperties())
{
if (src.Name == tar.Name)
{
target.GetProperty(tar.Name).SetValue(tarObj, source.GetType().GetProperty(tar.Name).GetValue(source, null), null);
}
}
}
}
catch (Exception ex)
{
throw ex;
}
return tarObj;
}*/
}
}
2. Dao 从DataTable填充数据
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using Guc.Entity;
namespace Tuo.Dao
{
public class DoctorDao
{
#region --sql--
public Doctor GetDoctor(string tel, string doctorType)
{
string ehrID = ArchivesDao.GetArchievId(tel);
Doctor doctor = null;
if (!string.IsNullOrEmpty(ehrID))
{
string sql = string.Empty;
switch (doctorType)
{
case "1":
sql = home_doctor_sql;
break;
case "2":
sql = community_doctor_sql;
break;
}
if (!string.IsNullOrEmpty(sql))
{
DataTable table = DBHelper.GetTable(sql, new SqlParameter[] { new SqlParameter("@ehr_id", ehrID) });
doctor = EntityHelper.GetEntity<Doctor>(table);
}
}
return doctor;
}
#endregion
}
}
以上代码有无效率问题?多谢大家指点!