Home > Enterprise >  Expression Property by string
Expression Property by string

Time:01-18

I haven't worked with expressions that much, I am trying to reference an Expression property by string name but I cam getting this error:

c# The member expression must specify a property or method that is public and that belongs to the type Soly.Models.Profile (Parameter 'expression')

public class ProfileFilterType : FilterInputType<Profile> {
        protected override void Configure(
        IFilterInputTypeDescriptor<Profile> descriptor) {
            descriptor.BindFieldsExplicitly();

            descriptor.Field(f => Build<IFilterInputTypeDescriptor<Profile>, string>("firstName"));
        }

        public static Expression<Func<TClass, TProperty>> Build<TClass, TProperty>(string fieldName) {
            var param = Expression.Parameter(typeof(TClass));
            var field = Expression.PropertyOrField(param, fieldName);
            return Expression.Lambda<Func<TClass, TProperty>>(field, param);
        }
    }

descriptor.field signature:

IFilterFieldDescriptor Field<TField>(Expression<Func<T, TField>> propertyOrMember);

I am trying to iterate over the Profile properties with reflection and add a field descriptor for each in HotChocolate GraphQL.

CodePudding user response:

Change descriptor.Field(f => Build<IFilterInputTypeDescriptor<Profile>, string>("firstName")); to:

descriptor.Field(Build<Profile, string>("firstName"));

Otherwise your are creating an expression with following type Expression<Func<Profile, Expression<Func<IFilterInputTypeDescriptor<Profile>,string>>>> which is definitely not what is expected.

P.S.

Not sure, but should not something like descriptor.Field("firstName"); or descriptor.Field(p => p.firstName); just work without need to manually handle expression trees?

  • Related