Error accessing array indices inside a LINQ expression

Asked

Viewed 26 times

0

I am doing a query to search all weather with a certain date, but when executing occurs the following error:

An exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll but was not handled in user code

Additional information: The LINQ expression node type 'ArrayIndex' is not supported in LINQ to Entities.

Follow the code below:

var metereologias = from b in db.Metereologias.Where(b => b.data_de_leitura.Equals(tmp[i]))
                                   select new MetereologiaDTO()
                                   {
                                       metereologiaId = b.metereologiaId,
                                       data_de_leitura = b.data_de_leitura,
                                       hora_de_leitura = b.hora_de_leitura,
                                       temperatura = b.temp,
                                       vento = b.vento,
                                       pressão = b.pressao,
                                       NO = b.NO,
                                       NO2 = b.NO2,
                                       CO2 = b.CO2,
                                       Local = b.Local.Nome
                                   };
                List<MetereologiaDTO> tmpResult = new List<MetereologiaDTO>(metereologias);

1 answer

1


To fix the problem use a temporary variable to store the value in the index i of the matrix tmp:

var tempValue = tmp[i];
var metereologias = db.Metereologias.Where(b => b.data_de_leitura.Equals(tempValue))
                                    .Select(new MetereologiaDTO
                                    {
                                       metereologiaId = b.metereologiaId,
                                       data_de_leitura = b.data_de_leitura,
                                       hora_de_leitura = b.hora_de_leitura,
                                       temperatura = b.temp,
                                       vento = b.vento,
                                       pressão = b.pressao,
                                       NO = b.NO,
                                       NO2 = b.NO2,
                                       CO2 = b.CO2,
                                       Local = b.Local.Nome
                                    }).ToList();

var result = new List<MetereologiaDTO>(metereologias);

If you use a matrix index tmp[i] within an Expression Tree, it will attempt to convert this into an expression as well, causing error.

UPDATED

I’ve updated the code by adopting a standard - doing all the commands through the fluent interface, but the way you wrote your code will work the same.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.