如何在函数内部设置对象的 属性 值?

How to set property value of object inside function?

我正在使用 entity framework 以及存储库模式来与数据库交互。

为了简单起见,我正在做这样的事情。

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

我想做的不是更改函数外的实体,而是希望能够传入表达式来更新对象。

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
}

例如

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

Customer 将为 null,需要查找。那部分有效。

我需要将客户的名字更新为 john,其中 Id == 4。 我想传递表达式并将其附加到要更新的 dbEntity。

x => x.FirstName = "John"

应该以某种方式变成

dbEntity.FirstName = "John"

我该怎么做?

好的,这就是我最后做的。我发现 this function 似乎可以解决问题。

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);
}

我在我的更新函数中调用它

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;
}

我这样称呼它

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