简体   繁体   English

LINQ 表达式无法翻译!? 为什么?

[英]The LINQ expression could not be translated!? why?

I'm trying to retrieve a few records from a table given a certain condition... this is my code:我试图在给定条件的情况下从表中检索一些记录......这是我的代码:

var areas = _context.Set<T>()
                .Where(p => (int)p.GetType().GetProperty(campoOrdem).GetValue(p) >= indexMin &&
                    (int)p.GetType().GetProperty(campoOrdem).GetValue(p) <= indexMax).ToList();

I am getting this error :我收到此错误:

'The LINQ expression 'DbSet<RH_Cargos> .Where(r => (int)r.GetType().GetProperty(__campoOrdem_0).GetValue(r) >= __indexMin_1 && (int)r.GetType().GetProperty(__campoOrdem_0).GetValue(r) <= __indexMax_2)' could not be translated. 'LINQ 表达式 'DbSet<RH_Cargos> .Where(r => (int)r.GetType().GetProperty(__campoOrdem_0).GetValue(r) >= __indexMin_1 && (int)r.GetType().GetProperty(__campoOrdem_0) .GetValue(r) <= __indexMax_2)' 无法翻译。

All of my variables are getting the correct values.. campoOrdem is the string which contains the name of the field, indexMin and indexMax is my values of order in the database, in the example, indexMin is 1, and indexMax is 2...我的所有变量都得到了正确的值.. campoOrdem 是包含字段名称的字符串,indexMin 和 indexMax 是我在数据库中的顺序值,在示例中,indexMin 为 1,indexMax 为 2 ...

what is happening?怎么了?

Reflection won't work for what you are trying to do, but if the property always has the same name, you could use generic constraints (if you can add that interface to all relevant entities):反射不适用于您要执行的操作,但如果属性始终具有相同的名称,您可以使用通用约束(如果您可以将该接口添加到所有相关实体):

 public interface IEntityWithCampoOrdem
 {
     public int CampoOrdem { get; } // property name should always be the same
 }

This assumes that entities like RH_Cargos can be defined like so:这假设像RH_Cargos这样的实体可以像这样定义:

 public class RH_Cargos : IEntityWithCampoOrdem
 {
      // other properties

      public int CampoOrdem { get; set; }
 }

Now you can create a generic method like so:现在您可以创建一个通用方法,如下所示:

 public void GetAreas<T>() where T : IEntityWithCampoOrdem
 {
     var areas = _context.Set<T>()
            .Where(p => p.CampoOrdem >= indexMin &&
                p.CampoOrdem <= indexMax).ToList();
 }

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

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