0

我有这样的Update方法:

public void Update(MyClass item, System.Linq.Expressions.Expression<Func<MyClass, bool>> exp)

我像这样更新状态字段:

MyClass  u = ent.MyClass.Where(exp).FirstOrDefault();
if (u == null)
{
    throw new Exception("No Record Found");
}
else
{
    u.Status=item.Status;              <-------
    ent.SaveChanges();
}

好的,问题是我想将此更新方法用于各种更新,例如用户可能想要更新status,NameTel,fax,Address,name...

我想检查我的属性是否为空,它分配给选定对象的类似属性(在用箭头显示的行中)。我怎么能自动做到这一点?我不想要这样的:

if(item.Status != null)
{
     u.Status = item.Status;
}
if(item.Name != null)
{
     u.Name = item.Name;
}
,....

谢谢

4

2 回答 2

3
MyClass item = new MyClass() { Name = "aaa" };
MyClass u = new MyClass() { Name = "uuu", Status = "ssss" };

MyCopy(item, u);

void MyCopy<T>(T src, T dest)
{
    var notNullProps = typeof(T).GetProperties()
                                .Where(x=>x.GetValue(src,null)!=null);

    foreach (var p in notNullProps)
    {
        p.SetValue(dest, p.GetValue(src, null));
    }
}
于 2012-10-14T11:53:02.457 回答
1

您可以use reflection检查是否为空。唯一的开销是将propertyName显式传递给您的方法 -

public void Update(MyClass item, Expression<Func<MyClass, bool>> exp,
                                            string propertyName)
{
   object propertyValue = item.GetType().GetProperty(propertyName)
                               .GetValue(item, null);
   if(propertyValue != null)
   {
      // do your stuff here
   }
}
于 2012-10-14T11:54:40.757 回答