Even Though I check my IEnumerable for null I still get a null exception...why?
How can line 25 in the code below generate the error that follows? I'm baffled. ProductSuggestions is IEnumerable<Product> ProductSuggestions
Line 24: <%if (Model.ProductSuggestions != null) { %>
Line 25: <%if (Model.ProductSuggestions.Any()) {
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 i开发者_运维技巧t originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Are you positive the issues is on line 25 and not line 24? Try making line 24
<%if (Model != null && Model.ProductSuggestions != null) { %>
And see if you get the same error. My guess is that you will not.
Could the NullReferenceException refer to members of the ProductSuggestions object?
I just recently ran into an issue where I checked a parent object for null, but as soon as I tried to access any child properties, I received the NullReferenceException.
I apologize, but based on the info I gave this problem was not going to be easy to solve.
After sleeping on it, it dawned on me that even though I was typing my list as IEnumerable
it was really still an IQueryable
as that's how it came out of my LINQ query in my Repository. With the deferred execution of IQueryable
the issue was not becoming apparent until I called .Count()
or .Any()
on the set in the View.
The problem was really located in the Repository where I had a LINQ query setup that did not account for a possible NULL.
So, answer would have been: You idiot, are you sure you're dealing with IEnumerable
and not IQueryable
? And if this is really an IQueryable
, are you sure the problem is not located in the LINQ query itself, and not in the place where it is being executed? :)
Evaluating a query (whether IEnumerable or IQueryable) is a potential source of exceptions, even when the query itself is not null.
Customer c = null;
List<Customer> customers = new List<Customer>() {c};
IEnumerable<Customer> query = customers.Where(x => x.Name == "Bob");
if (query != null)
{
Console.WriteLine("query is not null");
}
try
{
bool result = query.Any();
}
catch
{
Console.WriteLine("null exception when query was evaluated");
}
精彩评论