Pass the property of the Linq object in the method of setting and obtaining the result

I am trying to pass a Linq object property that will be used by my method. I can easily pass property to request

Func<Entities.MyEntity, ResultType> GetProperty = ent => ent.Property;

However, this returns a ResultType and cannot be used to set the property.

I thought about using reflection to get the Info property, but that would allow me to get the property, but then I cannot use Linq syntax to call my property. Is there a guru who knows how to do this?

I have a hunch that I can do this by building a piece of the expression tree and applying it to the query ...

I really hoped to do something like:

var value = myQueryEntity.CallMagicFunction();  //typesafe
myQueryEntity.CallMagicFunction() = value; //typesafe
+3
source share
1 answer

, ; basic (/ ):

static MemberInfo ReadMember(LambdaExpression expr)
{
    if(expr == null) throw new ArgumentNullException("expr");
    MemberExpression me = expr.Body as MemberExpression;
    if(me == null || !ReferenceEquals(me.Expression, expr.Parameters[0])) {
        throw new ArgumentException("expr");
    }
    return me.Member;
}

Expression<Func<Customer, int>> func = c => c.Id;
MemberInfo member = ReadMember(func);
// for simplicity assume prop:
PropertyInfo prop = (PropertyInfo)member;

; , get/set ( ) GetValue/SetValue.

, .NET 4.0 Expression ( # , Expression ).

+3

Source: https://habr.com/ru/post/1730827/


All Articles