How to convert PropertyInfo to property expression and use it to invoke generic method?

前端 未结 3 1338
耶瑟儿~
耶瑟儿~ 2020-12-15 10:22

How to convert PropertyInfo to property expression which can be used to invoke StructuralTypeConfiguration.Ignore(Expression

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-15 10:36

    Property expressions require the property access to be on a specific object. There's a few options you can take here. First, if this is being done within one of your entity objects, you can simple use a ConstantExpression to build the property expression:

    // Already have PropertyInfo in propInfo
    Expression.Property(Expression.Constant(this, this.GetType()), propInfo)
    

    However, since you need a Expression>, then it seems like you're going to have to build it using a ParameterExpression:

    ParameterExpression pe = Parameter.Expression(typeof(MyEntity), "eParam");
    Expression propExp = Expression.Property(pe, propInfo);
    

    HOWEVER, here's the kicker... This is just a MemberExpression. To convert to the expression you need, you need to use Expression.Lambda to get a Func<> expression of the type you need. The problem? You don't know the type of the property to define the generic parameters of the lambda expression!

    Expression> eFunc = Expression.Lambda>(propExp, pe);
    

    This is the crux of the problem of doing it this way. That's not to say it can't be done... It's just that using this method IN THIS WAY isn't going to work. You'll have to use a bit runtime and static typing trickery (as well as judicious use of Actions instead of Funcs) to get this to work correctly.

提交回复
热议问题