简体   繁体   English

C# 在 Lambda 表达式中使用反射中的 PropertyInfo,错误:不是有效的属性表达式

[英]C# using PropertyInfo from reflection in a Lambda expression, error: not a valid property expression

I have a loop where I'd like to loop through only properties of my object with a specific decorator/attribute, and for those properties, if they're null, then remove them from being in a modified state by Entity Framework.我有一个循环,我只想循环遍历具有特定装饰器/属性的对象的属性,对于这些属性,如果它们为空,则将它们从处于修改状态的实体框架中删除。 I can get the loop to work, but not the removal of them being tracked.我可以让循环工作,但不能删除正在跟踪的它们。

This is my attempt:这是我的尝试:

                // Protect [NullUpdateIgnoreAttribute] attributes from nullification
                var properties = updateCustomer.GetType().GetProperties().Where(
                    prop => Attribute.IsDefined(prop, typeof(NullUpdateIgnoreAttribute)));

                foreach (var p in properties)
                {
                    Console.WriteLine($"Verifying {p.Name}...");
                    object value = p.GetValue(updateCustomer, null);
                    if (value == null)
                    {
                        Console.WriteLine($"{p.Name} is null. Shielding attribute.");
                        loyalty.Entry(customer).Property(x => p.Name).IsModified = false; 
                    }
                }

It's failing due to what I'm passing into loyalty.Entry().Property(x => here).IsModified = false .由于我传递给loyalty.Entry().Property(x => here).IsModified = false它失败了。 Clearly I can't use the propertyInfo directly.显然我不能直接使用propertyInfo If I were doing this normally, I'd just pass x => x.propertyname .如果我通常这样做,我只会传递x => x.propertyname (eg x.firstname ) but I can't hard code the property name here, it could be any one of several properties that have this attribute. (例如x.firstname )但我不能在这里对属性名称进行硬编码,它可以是具有此属性的多个属性中的任何一个。

The error thrown is:抛出的错误是:

    "message": "The expression 'x => value(LCSApi.Customer+<>c__DisplayClass22_2).p.Name' is not a valid property expression. The expression should represent a simple property access: 't => t.MyProperty'. (Parameter 'propertyAccessExpression')",

有一个接受属性名称作为string重载,因此您可以使用它:

loyalty.Entry(customer).Property(p.Name).IsModified = false;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM