Linq表达式-设置嵌套的属性值
本文关键字:属性 嵌套 设置 表达式 Linq | 更新日期: 2023-09-27 18:07:47
我一直在使用以下方法将某些属性设置为null
,效果很好:
public static void Detach<TObject>(TObject parentObj, params Expression<Func<TObject, object>>[] detachEntities)
{
foreach (var detachEntity in detachEntities)
{
var prop = (PropertyInfo)((MemberExpression)detachEntity.Body).Member;
prop.SetValue(parentObj, null);
}
}
调用该方法,我使用:Detach(personObj, x => x.Car)
-非常简单
但是我正在尝试做以下事情:
Detach(personObj, x => x.Car.Make);
或者
Detach(personObj, x => x.Dogs.Select(s => s.Breed), x => x.Car.Make);
因此,我试图获得表达式中的每个属性并将其值设置为null
。
任何帮助都将是感激的。谢谢!
好的,所以这可能不是完美的,但它的工作-我是开放的任何改进:
public static void Detach<TObject>(TObject parentObj, params Expression<Func<TObject, object>>[] detachEntities)
{
foreach (var detachEntity in detachEntities)
{
var methodCallExpression = detachEntity.Body as MethodCallExpression;
var member = methodCallExpression?.Arguments[0] as MemberExpression;
PropertyInfo prop;
if (member != null)
{
prop = (PropertyInfo)member.Member;
prop.SetValue(parentObj, null);
}
var memberExpression = detachEntity.Body as MemberExpression;
var expression = memberExpression?.Expression as MemberExpression;
switch (memberExpression?.Expression.NodeType)
{
case ExpressionType.Parameter:
prop = (PropertyInfo)memberExpression.Member;
prop.SetValue(parentObj, null);
break;
case ExpressionType.MemberAccess:
if (expression != null)
{
prop = (PropertyInfo)expression.Member;
prop.SetValue(parentObj, null);
}
break;
}
}
}