1.定义model
class UserModel
{
/// <summary>
/// 元素特性 可以指定多个 如:[Column(Name ="username", DbType = "int")]
/// </summary>
[Column(Name ="username")]
public string name { get; set; }
[Column(Name = "userpwd")]
public string pwd { get; set; }
}
2.引入命名空间
using System.Data.Linq.Mapping;
using System.Reflection;
3.创建测试数据
//创建测试数据
DataTable dt = new DataTable();
dt.Columns.Add("username", typeof(string));
dt.Columns.Add("userpwd", typeof(string));
DataRow dr = dt.NewRow();
dr["username"] = "zhangsan";
dr["userpwd"] = "123";
dt.Rows.Add(dr);
// 测试数据创建结束
UserModel user = new UserModel();
//通过反射 获取UserModel类的所有属性集合
PropertyInfo[] properties = user.GetType().GetProperties();
// 遍历 属性集合
foreach (PropertyInfo f in properties)
{
// 获取属性的 特性
object[] o = f.GetCustomAttributes(typeof(System.Data.Linq.Mapping.ColumnAttribute), false);
if (o.Length == 0) continue;
ColumnAttribute[] columns = o as System.Data.Linq.Mapping.ColumnAttribute[];
if (columns.Length == 0) continue;
// 检测表中是否存在列
if (!dt.Columns.Contains(columns[0].Name)) continue;
// 获取特性 Name 值
// this.textEdit1.Text += columns[0].Name;
// 判断属性的类型 - 赋值
if (dt.Rows[0][columns[0].Name] == DBNull.Value)
{
if (f.PropertyType == typeof(int))
{
f.SetValue(user, 0, null);
}
if(f.PropertyType == typeof(string))
{
f.SetValue(user, "", null);
}
if (f.PropertyType == typeof(DateTime))
{
f.SetValue(user, null, null);
}
}
else
{
// 设置 对象属性 的值
f.SetValue(user, dt.Rows[0][columns[0].Name], null);
}
}
注:
可以新建类 集成自 ColumnAttribute , 添加自定义特性元素, 继承自 Attribute
[AttributeUsage(AttributeTargets.Property,AllowMultiple =true,Inherited =false)]
public class ColumnAttributeExt : Attribute
{
public string Fied { get; set; }
}
使用:
[ColumnAttributeExt(Fied ="name")]
public string ss { get; set; }