简体   繁体   中英

How to set property value of object inside function?

I am using entity framework along with a repository pattern to interact with the database.

For simplicity I am doing something like this.

public T Update(T entity)
{
     // Update Entity
}

What I am wanting to do instead of changing the entity outside the function, I want the ability to pass in the expression to update the object with.

public T Update(T entity, ItemINeedPassedIn, Expression<Func<TDBTable, bool>> predicate)
{
     var dbEntity = await GetOneAsync(predicate); // Which fetches me the entity to change

     // Code to attach the property value to entity goes here <-- This is what I need

     // Update Entity
}

For example

Update(Customer, x => x.FirstName = "John", x => x.Id == 4);

Customer would be null which requires the lookup. That part works.

I need to update the first name of the customer to john where Id == 4. I want to pass in the expression and attach that to the dbEntity to be updated.

x => x.FirstName = "John"

should somehow become

dbEntity.FirstName = "John"

How Do I do this?

Ok, here is what I ended up doing. I found this function which seems to do the trick.

public static void SetEntityValue(TDBTable entity, Expression<Func<TDBTable, object>> expression, object value)
{
    ParameterExpression valueParameterExpression = Expression.Parameter(typeof(object));
    Expression targetExpression = expression.Body is UnaryExpression ? ((UnaryExpression)expression.Body).Operand : expression.Body;

    var newValue = Expression.Parameter(expression.Body.Type);
    var assign = Expression.Lambda<Action<TDBTable, object>>
    (
        Expression.Assign(targetExpression, Expression.Convert(valueParameterExpression, targetExpression.Type)),
        expression.Parameters.Single(),
        valueParameterExpression
    );

    assign.Compile().Invoke(entity, value);
}

I call it within my update function

public T Update(TDBTable entity, Expression<Func<TDBTable, object>> expression, object value,
        Expression<Func<TDBTable, bool>> predicate)
{
     var dbEntity = await GetOneAsync(predicate); // Which fetches me the entity to change

     // Sets the variable
     SetEntityValue(result, expression, value);

     // Update Entity
     result = await EditAsync(result);

     return entity;
}

I call it like this

Update(new Customer(), x => x.FirstName, "John", x => x.Id == 4);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM