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

问题描述 投票:1回答:1

我正在使用实体框架以及存储库模式来与数据库进行交互。

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

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
}

例如

更新(Customer,x => x.FirstName =“John”,x => x.Id == 4);

客户将为null,这需要查找。那部分有效。

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

x => x.FirstName =“约翰”

应该以某种方式成为

dbEntity.FirstName =“John”

我该怎么做呢?

c# object reflection expression entity
1个回答
0
投票

好的,这就是我最终做的事情。我发现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;
}

我这样称呼它

更新(new Customer(),x => x.FirstName,“John”,x => x.Id == 4);

© www.soinside.com 2019 - 2024. All rights reserved.