【问题标题】:Set Properties that not null using linq and reflection使用 linq 和反射设置不为空的属性
【发布时间】:2012-10-14 11:39:59
【问题描述】:

我有一个像这样的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;
}
,....

谢谢

【问题讨论】:

    标签: c# linq entity-framework c#-4.0 reflection


    【解决方案1】:
    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));
        }
    }
    

    【讨论】:

      【解决方案2】:

      您可以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
         }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-10-11
        • 1970-01-01
        • 2021-02-21
        • 1970-01-01
        相关资源
        最近更新 更多