vendredi 18 septembre 2020

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. Clearly I can't use the propertyInfo directly. If I were doing this normally, I'd just pass x => x.propertyname. (e.g. x.firstname) but I can't hard code the property name here, it could be any one of several properties that have this attribute.

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')",




Aucun commentaire:

Enregistrer un commentaire