C# 实体类与数据表之间的映射

Igor C/C++/C# 数据库评论22,765字数 1638阅读5分27秒阅读模式

public class BaseEntity<T> where T : BaseEntity<T>
{
public BaseEntity()
{

}

public BaseEntity(DataTable table, int indexRow)
{
InitObjInfo(table, indexRow);
}

/// <summary>
/// 初始化实体类对象信息
/// </summary>
/// <param name="table"></param>
/// <param name="indexRow"></param>
private void InitObjInfo(DataTable table, int indexRow)
{
for (int i = 0; i < table.Columns.Count; i++)
{
// 按列的名称,从当前对象中获取同名属性
PropertyInfo pInfo = this.GetType().GetProperty(table.Columns[i].ColumnName);

// 存在该属性
if (pInfo != null)
{
object value = table.Rows[indexRow][table.Columns[i].ColumnName];
value = value == DBNull.Value ? string.Empty : value;
// 如果对象属性定义的类型和table的列的类型一致
if (pInfo.PropertyType == table.Columns[i].DataType)
{
pInfo.SetValue(this, value, null);
}
else
{
// 如果对象类型是枚举类型
if (pInfo.PropertyType.IsEnum)
{
// 数据库中保存的是int类型,则直接为枚举赋值
if (value.GetType() == typeof(int))
{
pInfo.SetValue(this, value, null);
}

// 如果数据库中保存的是string类型
if (value.GetType() == typeof(string))
{
pInfo.SetValue(this, Enum.Parse(pInfo.PropertyType, value.ToString(), false), null);//赋值
}
}
}
}
}
}

/// <summary>
/// 返回一个类型为T的对象
/// </summary>
/// <param name="table">数据表</param>
/// <param name="rowIndex">表中的第几行</param>
/// <returns>object</returns>
protected static T CreateInstance(DataTable table, int rowIndex)
{
if (table == null)
{
return null;
}
if (table.Rows.Count > rowIndex)
{
// 使用反射创建对象
return (T)System.Activator.CreateInstance(typeof(T), table, rowIndex);
}
else
{
return null;
}
}

/// <summary>
/// 返回一个泛型列表
/// </summary>
/// <param name="table">数据表</param>
/// <returns></returns>
protected static List<T> CreateInstances(DataTable table)
{
List<T> instances = new List<T>();

for (int i = 0; i < table.Rows.Count; i++)
{
T instance = CreateInstance(table, i);
if (instance != null)
{
instances.Add(instance);
}
}
return instances;
}
}

来源: C# 实体类与数据表之间的映射 - Thinker_cxz - 博客园

文章末尾固定信息

weinxin
我的微信
我的微信
一个码农、工程狮、集能量和智慧于一身的、DIY高手、小伙伴er很多的、80后奶爸。
 
Igor
  • 本文由 Igor 发表于 2019-02-2117:08:07
  • 实体类
  • 数据表
  • 映射
匿名

发表评论

匿名网友
:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:
确定

拖动滑块以完成验证