How set value a property selector Expression<Func<T,TResult>>

c# expression get property value
c# expression set property value
c# expression tree get property value
get value from linq expression
c# select property expression
c# get property using expression
expression property example c#
c# set property by name

i need associate a entity property Address in my Person class entity with expressions linq in my FactoryEntities class using pattern factory idea, look this is what I have and I want to do:

Address address = new Address();
address.Country = "Chile";
address.City = "Santiago";
address.ZipCode = "43532";
//Factory instance creation object
//This is idea
Person person = new FactoryEntity<Person>().AssociateWithEntity(p=>p.Address, address);

public class Person: Entity
{
    public string Name{ get; set; }
    public string LastName{ get; set; }
    public Address Address{ get; set; }
}

public class Address: Entity
{
    public string Country{ get; set; }
    public string City{ get; set; }
    public string ZipCode{ get; set; }
}

public class FactoryEntity<TEntity> where TEntity : Entity
{
    public void AssociateWithEntity<TProperty>(Expression<Func<TEntity, TProperty>> entityExpression, TProperty newValueEntity) where TProperty : Entity
    {
        if (instanceEntity == null || instanceEntity.IsTransient())
            throw new ArgumentNullException();

        /*TODO: Logic the association and validation 
        How set the newValueEntity into the property of entityExpression (x=>x.Direccion = direccion*/
    }
}
This works:

The following helper method converts a getter expression into a setter delegate. If you want to return an Expression<Action<T,TProperty>> instead of an Action<T,TProperty>, just don't call the Compile() method at the end.

Note: The code is from Ian Mercer's blog: http://blog.abodit.com/2011/09/convert-a-property-getter-to-a-setter/

    /// <summary>
    /// Convert a lambda expression for a getter into a setter
    /// </summary>
    public static Action<T, TProperty> GetSetter<T, TProperty>(Expression<Func<T, TProperty>> expression)
    {
        var memberExpression = (MemberExpression)expression.Body;
        var property = (PropertyInfo)memberExpression.Member;
        var setMethod = property.GetSetMethod();

        var parameterT = Expression.Parameter(typeof(T), "x");
        var parameterTProperty = Expression.Parameter(typeof(TProperty), "y");

        var newExpression =
            Expression.Lambda<Action<T, TProperty>>(
                Expression.Call(parameterT, setMethod, parameterTProperty),
                parameterT,
                parameterTProperty
            );

        return newExpression.Compile();
    }

[SOLVED], This works: The following helper method converts a getter expression into a setter delegate. If you want to return an Expression<Action<T  The parameter would be an Expression<Func<Customer,string>> selector. Reading it can be via flat compile: Reading it can be via flat compile: Func<Customer,string> func = selector.Compile();

You can set the property like this:

public void AssociateWithEntity<TProperty>(
    Expression<Func<TEntity, TProperty>> entityExpression,
    TProperty newValueEntity)
    where TProperty : Entity
{
    if (instanceEntity == null)
        throw new ArgumentNullException();

    var memberExpression = (MemberExpression)entityExpression.Body;
    var property = (PropertyInfo)memberExpression.Member;

    property.SetValue(instanceEntity, newValueEntity, null);
}

This will work only for properties, not fields, although adding support for fields should be easy.

But the code you have for getting the person won't work. If you want to keep the void return type of AssociateWithEntity(), you could do it like this:

var factory = new FactoryEntity<Person>();
factory.AssociateWithEntity(p => p.Address, address);
Person person = factory.InstanceEntity;

Another option is a fluent interface:

Person person = new FactoryEntity<Person>()
    .AssociateWithEntity(p => p.Address, address)
    .InstanceEntity;

Delegate that selects a writable property on a generic, FieldType); // This is the assignment expression (sets the field to the parameter value). var assign = Expression.Assign(fieldExpr, rightExpr);  How to set property value using Expressions? [duplicate] Ask Question Asked 7 years, How set value a property selector Expression<Func<T,TResult>> 0.

Another solution is to get property owner ant invoke property setter using reflection. The advantage of this solution that it does not use extension methods and can be call with any type

private void SetPropertyValue(Expression<Func<object, object>> lambda, object value)
{
    var memberExpression = (MemberExpression)lambda.Body;
    var propertyInfo = (PropertyInfo)memberExpression.Member;
    var propertyOwnerExpression = (MemberExpression)memberExpression.Expression;
    var propertyOwner = Expression.Lambda(propertyOwnerExpression).Compile().DynamicInvoke();

    propertyInfo.SetValue(propertyOwner, value, null);            
}
...
SetPropertyValue(s => myStuff.MyPropy, newValue);

Attribute Ends With Selector [name$=”value”], value: An attribute value. Can be either a valid identifier or a quoted string. Example: Finds all inputs with an attribute name that  public static void InjectData<T>(this T data, Dictionary<Expression<Func<T, object>>, object> pairData) where T : IAuditable { foreach (var item in pairData) { var member = item.Key; // If member type is a reference type, then member.Body is the property accessor. // For value types it is Convert(property accessor) var memberBody = member.Body as MemberExpression ??

This is my solution that uses Expression.Assign, but after looking more closely, the accepted answer is just as good.

// optionally or additionally put in a class<T> to capture the object type once
// and then you don't have to repeat it if you have a lot of properties
public Action<T, TProperty> GetSetter<T, TProperty>(
   Expression<Func<T, TProperty>> pExpression
) {
   var parameter1 = Expression.Parameter(typeof(T));
   var parameter2 = Expression.Parameter(typeof(TProperty));

   // turning an expression body into a PropertyInfo is common enough
   // that it's a good idea to extract this to a reusable method
   var member = (MemberExpression)pExpression.Body;
   var propertyInfo = (PropertyInfo)member.Member;

   // use the PropertyInfo to make a property expression
   // for the first parameter (the object)
   var property = Expression.Property(parameter1, propertyInfo);

   // assignment expression that assigns the second parameter (value) to the property
   var assignment = Expression.Assign(property, parameter2);

   // then just build the lambda, which takes 2 parameters, and has the assignment
   // expression for its body
   var setter = Expression.Lambda<Action<T, TProperty>>(
      assignment,
      parameter1,
      parameter2
   );

   return setter.Compile();
}

Another thing you can do is encapsulate them:

public sealed class StrongProperty<TObject, TProperty> {
   readonly PropertyInfo mPropertyInfo;

   public string Name => mPropertyInfo.Name;
   public Func<TObject, TProperty> Get { get; }
   public Action<TObject, TProperty> Set { get; }
   // maybe other useful properties

   internal StrongProperty(
      PropertyInfo pPropertyInfo,
      Func<TObject, TProperty> pGet,
      Action<TObject, TProperty> pSet
   ) {
      mPropertyInfo = pPropertyInfo;
      Get = pGet;
      Set = pSet;
   }
}

And now you can pass these around, similar to delegates, and write code whose logic can vary by property. This gets around the fact that you can't pass properties by reference.

PropertyInfo selector using Lambda expressions, PropertyInfo selector using Lambda expressions Simply taking one scenario, if the property is refactored to a new name public string Name { get ; set ; } in C#Next PostReferencing local variable in anonymous delegates  We have a Person class with a Name (string) property. I could manually create a "property selector" like this propertySelector writing: Expression<Func<Person, string>> propertySelector = x => x.Name; But I would like to get the same property selector with my method. var propertySelector = CreatePropertySelectorExpression<Person, string>("Name");

That's the idea, i'm worked for me with this code, taking into account the contribution of svick:

public class FactoryEntity<TEntity> where TEntity : Entity, new()

{

private TEntity _Entity;

    public FactoryEntity()
    {
        _Entity = new TEntity();
    }

public TEntity Build()
    {
        if (_Entity.IsValid())
            throw new Exception("_Entity.Id");

        return _Entity;
    }

public FactoryEntity<TEntity> AssociateWithEntity<TProperty>(Expression<Func<TEntity, TProperty>> foreignEntity, TProperty instanceEntity) where TProperty : Entity
    {
        if (instanceEntity == null || instanceEntity.IsTransient())
            throw new ArgumentNullException();

        SetObjectValue<TEntity, TProperty>(_Entity, foreignEntity, instanceEntity);
        return this;
    }

private void SetObjectValue<T, TResult>(object target, Expression<Func<T, TResult>> expression, TResult value)
    {
        var memberExpression = (MemberExpression)expression.Body;
        var propertyInfo = (PropertyInfo)memberExpression.Member;
        var newValue = Convert.ChangeType(value, value.GetType());
        propertyInfo.SetValue(target, newValue, null);
    }
}

Here I call the factory for me to build the Person object in a valid

Person person = new FactoryEntity<Person>().AssociateWithEntity(p=>p.Address, address).Build();

But I do not know if this code is optimal or not, at least I do not make a call to compile() method, what are saying?

thanks

Selectors, The following table summarizes CSS 2.1 selector syntax: E[foo], Matches any E element with the "foo" attribute set (whatever the value). Care has to be taken that all property declarations that are to apply only to the default case are overridden Thus, for HTML, div.value and div[class~=value] have the same meaning. Property Expression for the LoggingMode Property of a Package. The following property expression can be used to set the LoggingMode property of a package. The expression uses the DAY and GETDATE functions to get an integer that represents the day datepart of a date. If the day is the 1st or 15th, logging is enabled; otherwise, logging is disabled.

Get Property Names Using Lambda Expressions in C#, Build utility to get the properties names from the lambda expressions. set the properties not to be asserted as lambda expression instead of plain text. to get the name of a property, a void method or a value type method. This is done by passing a specially crafted hashtable to the Property parameter rather than a static property name. To modify the output with calculated properties requires a hashtable with a Name and an Expression key. The name key is the property name and the Expression key is a scriptblock that will be executed as Select-Object receives input.

[SOLVED], You cannot invoke CLR delegates so simply in sql. But you can pass in the property selector as an Expression tree., so your signature would be  An expression is a combination of mathematical or logical operators, constants, functions, table fields, controls, and properties that evaluates to a single value. You can use expressions in Access to calculate values, validate data, and set a default value.

Selectors, There are several ways to get a value of an attribute. First, one Selector also has a .re() method for extracting data using regular expressions. sel.xpath('//a//​text()').getall() # take a peek at the node-set ['Click here to go to the ', 'Next Page'] >  Properties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code. A get property accessor is used to return the property value, and a set property accessor is used to assign a new value. These accessors can have different access levels.

Comments
  • The propertyInfo you have there is for a TEntity, not a TProperty. You cannot use it to access a property for an object of a different type. Which way is the association supposed to go? What you're trying to do here doesn't make sense to me.
  • It's very buggy code, and is not easy say what you want please clarify it.
  • I'm sorry the explanation was not clear, but i want to do is to occupy a factory that allows me to relate objects to intercepting validate the association so it is properly check
  • possible duplicate of Property selector Expression<Func<T>>. How to get/set value to selected property
  • How do you call this method? I can't seem to get the correct arguments into the delegate.
  • @hbob , something like: GetSetter( (string example) => example.Length )
  • How about if you don't know TProperty? Using Expression.Lambda<Action<T, object>> does not work :(
  • @markmnl stackoverflow.com/questions/729295/… might help
  • @DaveCousineau maybe, have you checked the IL for this answer and for yours? I do know that this answer is pretty old, and that Expression.Assign came along in .NET 4.0 whereas @IanMercer's code is compatible with .NET 3.5 . I'm not sure if there's a difference in what actually gets executed though - we'd need to test it
  • lambda.Body may be UnaryExpression, see stackoverflow.com/questions/12420466/…
  • Here is a GetProperty solution for nested expressions (multiple dots): codeproject.com/Articles/733296/…