Set Properties that not null using linq and reflec

2019-09-09 06:51发布

I have a Update method like this:

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

and I update status field like this:

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

ok ,the problem is I want to use this update method for various updates for example user may want to update status,Name or Tel,fax,Address,name and ...

I want to check I property isn't null it assign to similar property of selected object(in line that show with arrow). How I can to this automatically ? I don't want wtite like this:

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

thanks

2条回答
啃猪蹄的小仙女
2楼-- · 2019-09-09 07:11

You can use reflection to check for null. Only overhead would be to pass the propertyName explicitly to your method -

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
   }
}
查看更多
贼婆χ
3楼-- · 2019-09-09 07:23
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));
    }
}
查看更多
登录 后发表回答