使用linq和反射设置不为null的属性 [英] Set Properties that not null using linq and reflection

查看:107
本文介绍了使用linq和反射设置不为null的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个更新方法,如下所示:

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属性不是null,它分配给选定对象的相似属性(在用箭头显示的行中)。我怎么能自动地?我不想要这样的wtite:

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

感谢

推荐答案

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

这篇关于使用linq和反射设置不为null的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆