Linq表达式 - 设置嵌套属性值

时间:2016-09-20 11:32:53

标签: c# linq

我一直在使用以下方法将某些属性设置为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);

-OR -

Detach(personObj, x => x.Dogs.Select(s => s.Breed), x => x.Car.Make);

因此,我试图获取表达式中的每个属性,并将其值设置为null

任何帮助将不胜感激。 谢谢!

1 个答案:

答案 0 :(得分:0)

好的,所以这可能不完美,但它正在发挥作用 - 我对任何改进持开放态度:

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