簡體   English   中英

使用linq和Reflection設置不為空的屬性

[英]Set Properties that not null using linq and reflection

我有一個像這樣的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和...

我想檢查我的屬性是否為null,它分配給所選對象的相似屬性(在顯示箭頭的行中)。 我怎么能自動做到這一點? 我不想這樣:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM