博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

PropertyInfo.SetValue的使用(以及结合Entity FrameWork)

Posted on 2010-06-29 10:08  Hyperional  阅读(2069)  评论(0)    收藏  举报

 当实体对象的属性过多时,可考虑使用PropertyInfo.SetValue方法:

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中:

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;
}