简体   繁体   English

我可以在Linq表达式中将String参数用作实体属性和对象属性吗?

[英]Can I use String parameter as an entity property and an object property in Linq expression?

This is my first question, I'm doing the best I can to be understand. 这是我的第一个问题,我正在尽我所能理解。

I want to insert in table that has many unique properties. 我要插入具有许多唯一属性的表中。

I want to use string instead of property in a Linq expression. 我想在Linq表达式中使用字符串而不是属性。

I want to make something like this: 我想做这样的事情:

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

I tried many solutions proposed on StackOverflow but neither worked for my case. 我尝试了在StackOverflow上提出的许多解决方案,但均不适用于我的情况。

I tried these solutions: 0 , 1 , 2 , 3 , and many others, but none of those solutions works for my case. 我尝试这些解决方案: 0123 ,和许多其他人,但没有这些解决方案适用于我的情况。

I expect the result.count to be 0 or higher, but when I tried this solution , I got this error : 我期望result.count为0或更高,但是当我尝试此解决方案时 ,出现此错误:

LINQ to Entities does not recognize propertyInfo.GetValue. LINQ to Entities无法识别propertyInfo.GetValue。

Any suggestions? 有什么建议么?

You could try dynamic linq . 您可以尝试使用动态linq It's a bit old, but it allows you to do things like: 它有点旧,但是它允许您执行以下操作:

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

In your case it would be something like: 在您的情况下,它将类似于:

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

As from your example: 根据您的示例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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