当前位置:   article > 正文

mysql表 c#实体类_C# 实体类与数据表之间的映射

c# 服务api 实体类 映射数据表

public class BaseEntity where T : BaseEntity

{

public BaseEntity()

{

}

public BaseEntity(DataTable table, int indexRow)

{

InitObjInfo(table, indexRow);

}

///

/// 初始化实体类对象信息

///

///

///

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);//赋值

}

}

}

}

}

}

///

/// 返回一个类型为T的对象

///

/// 数据表

/// 表中的第几行

/// object

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;

}

}

///

/// 返回一个泛型列表

///

/// 数据表

///

protected static List CreateInstances(DataTable table)

{

List instances = new List();

for (int i = 0; i < table.Rows.Count; i++)

{

T instance = CreateInstance(table, i);

if (instance != null)

{

instances.Add(instance);

}

}

return instances;

}

}

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/253692
推荐阅读
相关标签
  

闽ICP备14008679号