Ok I'm having this problem that is driving me crazy, I'm doing a search for a website, and it works great on my machine but when I upload it to gearhost it just blow with this error :
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 43: @if (Model != null)
Line 44: {
Line 45: if (Model.Any())
Line 46: {
The error appear on Line 45, even though I'm sure I know its not null and its and IEnumerable.
My Model in razor is declared as follow:
@model IEnumerable<Posada>
And this does work if I send an empty search, but not when I use a string that returns rows or other that does not return any.
In my controller I just return a IEnumerable and use it as the model.
IEnumerable<Posada> posadas = unitOfWork.PosadaRepository.Get(includeProperties: "Estado,Lugar")
.Where(p => p.Nombre.ToLowerInvariant().Contains(query) ||
p.Estado.Nombre.ToLowerInvariant().Contains(query) ||
p.Lugar.Nombre.ToLowerInvariant().Contains(query))
.OrderBy(p => p.Id)
.Skip((page - 1)*pagingInfo.ItemsPerPage)
.Take(pagingInfo.ItemsPerPage);
Remember IEnumerable<>
only evaluates the query when it needs to, so as stated by the other answer, when you use Any()
, your query gets evaluated and in that case either Estado
or Lugar
can be null.
Try something like:
(p.Estado != null && p.Estado.Nombre.ToLowerInvariant().Contains(query)) ||
(p.Lugar != null && p.Lugar.Nombre.ToLowerInvariant().Contains(query)))