I have a method in web api that receives a model from a search form and according to its values, it starts to filter the result of this search, as shown 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 EntityCommandExecutionException
exception 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? Is there another way besides executing a toList()
before the call to navigationProperty?