4
I have a web api method that receives a model from a search form and according to its values, it starts to filter the result of this search, as an example below.
public HttpResponseMessage Buscar([FromBody]BuscarModel model)
{
Chamados resultado = chamadoServico.Buscar();
if(!string.IsNullOrWhiteSpace(model.Foo))
resultado = resultado.Where(e => e.Foo == model.Foo);
if(!string.IsNullOrWhiteSpace(model.Bar))
resultado = resultado.Where(e => e.Bar == model.Bar);
return Request.CreateResponse(HttpStatusCode.OK, resultado);
}
The code works as expected until you add a filter to a navigationProperty
. For example
if(model.Foobar != null && !string.IsNullOrWhiteSpace(model.Foobar.Foo))
resultado = resultado.Where(e => e.Foobar.Foo == model.Foobar.Foo);
At this point, the exception EntityCommandExecutionException
is raised with the following message:
There is already an open Datareader associated with this Command that should be closed first.
Is this the right way to create a search engine through filters?
What can be done to prevent the exception from being raised? There is another way besides executing a toList()
before the call to navigationProperty?
I wanted to avoid precisely because of the possible mass of data, but leaving this filter as the last to be performed can decrease the processing load in SQL.
– Vinícius
The ideal is for you to leave as many filters as you can on Controller and filter a smaller mass in memory within the filter. It is a limitation yes, which I hope you solve in future versions.
– Leonel Sanches da Silva