PropertyInfo.SetValue的使用(以及结合Entity FrameWork)
Posted on 2010-06-29 10:08 Hyperional 阅读(2069) 评论(0) 收藏 举报当实体对象的属性过多时,可考虑使用PropertyInfo.SetValue方法:

public static T SetProperties<T>(T tObj, System.Data.DataRow Row)
{
if (tObj == null) throw new ArgumentNullException("tObj");
if (Row == null) throw new ArgumentNullException("Row");
foreach (System.Reflection.PropertyInfo Prop in tObj.GetType().GetProperties())
{
object [] objAttr = Prop.GetCustomAttributes(tObj.GetType(), true);
if (Row[Prop.Name] == null || Row[Prop.Name].ToString().Length < 1)
throw new Exception(string.Format("请为{0}提供一个有效的值.", Prop.Name));
Prop.SetValue(tObj, Row[Prop.Name], null);
}
return tObj;
}
在EF中:

public static T SetProperties<T>(T tObj, System.Data.DataRow Row)
{
if (tObj == null) throw new ArgumentNullException("tObj");
if (Row == null) throw new ArgumentNullException("Row");
foreach (System.Reflection.PropertyInfo Prop in tObj.GetType().GetProperties())
{
if (Row[Prop.Name] == null || Row[Prop.Name].ToString().Length < 1)
throw new Exception(string.Format("请为{0}提供一个有效的值.", Prop.Name));
object[] objAttr = Prop.GetCustomAttributes(tObj.GetType(), true);
int count = objAttr.Where(p => p is System.Data.Objects.DataClasses.EdmScalarPropertyAttribute).ToList().Count; //判断是否标量属性
if (count > 0)
{
Prop.SetValue(tObj, Row[Prop.Name], null);
}
}
return tObj;
}