【问题标题】:Can I use String parameter as an entity property and an object property in Linq expression?我可以在 Linq 表达式中使用 String 参数作为实体属性和对象属性吗?
【发布时间】:2019-07-12 13:57:26
【问题描述】:

这是我的第一个问题,我正在尽我所能理解。

我想在具有许多独特属性的表中插入。

我想在 Linq 表达式中使用字符串而不是属性。

我想做这样的事情:

public List<string> AddEmploye(Employe pEmploye)
{
   List<string> NonUnique = new List<string>();
   List<string> Prop = new List<string>
      {
         "ID",
         "NAS",
         "CODE",
      };

   foreach (var prop in Props)
   {
      var result = (from t in _context.TEMP02A
                  where t.prop == pEmploye.prop
                  select t.name).ToList();

      if (result.Count() > 0)
        NonUnique.Add(prop);
   }
   return NonUnique;
}

我尝试了StackOverflow 上提出的许多解决方案,但都不适用于我的情况。

我尝试了以下解决方案: 0, 1, 2, 3, 和许多其他的,但这些解决方案都不适用于我的情况。

我希望 result.count 为 0 或更高,但是当我尝试 this solution 时,我收到了这个错误:

LINQ to Entities 无法识别 propertyInfo.GetValue。

有什么建议吗?

【问题讨论】:

  • 嗨迈克尔,道具从何而来?另外,我不确定您的实际问题是什么,您能否尝试更清楚地解释您要做什么?
  • 看起来他正在尝试使用 EF 按字符串名称访问列,但我不确定。
  • 道具是我的实体属性,它们是我的数据库表中的唯一列。我想使用字符串而不是实体属性。目标是减少代码行的数量,因为我对 7 个实体属性重复相同的过程。
  • t_context.TEMP02A 表中的类型是什么?也是Employee吗?
  • 是的! tpEmploye 类型相同

标签: c# entity-framework properties linq-to-entities


【解决方案1】:

你可以试试dynamic linq。它有点旧,但它允许您执行以下操作:

Where($"property_name_as_string = @0", some_value)

在你的情况下,它会是这样的:

.Where(prop + " = @0",employee_prop_value_by_reflection_here)
.Select("Name");

从你的例子来看:

var val = GetPropValue(pEmploye, prop);
_context.TEMP02A.Where(prop + " = @0",val);

【讨论】:

  • 我试过这个:var result = _context.TEMP02A.Where($"property_name_as_string == some_value"); 但我得到了这个错误:无法从'字符串'转换为'System.Linq.Expression.Expression>'
  • 从您提出的建议开始,我继续这样做:var result = _context.TEMP02A.Where(t =&gt; GetPropValue(t,prop) == GetPropValue(pEmploye, prop)).Select(t =&gt; t.name);。这个执行但是当我添加一个.ToList()时,我继续这个错误:System.NotSupportedException: 'LINQ to Entities does not recognize the method 'System.Object GetPropValue(System.Object, System.String)' method, and this method cannot be translated into a store expression.'
  • 看起来GetValue() 方法在我的表达式中不起作用:(
  • 从你上一个例子来看,它说:No overload for method 'Where' takes 2 arguments
  • 您是否包含了动态 linq 库?你需要包括using System.Linq.Dynamic
猜你喜欢
  • 2015-12-23
  • 1970-01-01
  • 2017-07-26
  • 2019-05-14
  • 1970-01-01
  • 2022-07-27
  • 1970-01-01
  • 1970-01-01
  • 2014-09-24
相关资源
最近更新 更多