【问题标题】:How to set property value of object inside function?如何在函数内部设置对象的属性值?
【发布时间】:2019-04-09 23:30:32
【问题描述】:

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

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

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
}

例如

更新(客户,x => x.FirstName = "John",x => x.Id == 4);

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

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

x => x.FirstName = "约翰"

应该以某种方式变成

dbEntity.FirstName = "约翰"

我该怎么做?

【问题讨论】:

  • 什么是ItemINeedPassedIn?为什么将 4 分配给 Id?应该是x.Id == 4
  • ItemINeedToPassIn 是我正在寻找和更新的 Id == 4
  • 我觉得问题是:ItemINeedPassedIndbEntity的类型是什么?或者,您在致电Update 之前不认识他们吗?您知道谓词中x 的类型吗?我认为,最简单的回答方法是让你给我们一个输入和一个期望的输出,同时澄清类型是否已知。
  • 你真的需要Expression&lt;Func&lt;TDBTable, bool&gt;&gt;,还是只需要Func&lt;TDBTable, bool&gt;

标签: c# object reflection expression entity


【解决方案1】:

好的,这就是我最终要做的。我找到了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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-12
    • 1970-01-01
    • 2019-03-24
    • 1970-01-01
    • 1970-01-01
    • 2013-09-04
    • 2021-07-19
    相关资源
    最近更新 更多