Ricardo Figueiredo
Ricardo Figueiredo

Reputation: 216

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.

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...

what is happening?

Upvotes: 0

Views: 1053

Answers (1)

jeroenh
jeroenh

Reputation: 26782

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:

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

Upvotes: 2

Related Questions