Search code examples
asp.net-mvc-2argumentnullexception

Working around an ArgumentNullException


I'm trying to return the five most recent articles from my database so I can put links to them in some secondary navigation I have on my index page. I've divided up my MVC project into two sub-projects, based on Steven Sanderson's suggestion in his book - WebUI, which is the MVC portion, and Domain, which is the EF4/Domain model portion.

I have a rudimentary repository which does the heavy lifting, mainly by providing a facade to EF4, and handling other tasks like model validation. I have a simple method which returns the last five articles:

public List<Article> LastFive()
{
    return _siteDB.Articles.OrderByDescending(a => a.LastModified).Take(5).ToList();
}

My problem is that I have to use two other similar functions on my index page to show the five most recent reviews and site news items. With nothing in the db, they return ArgumentNullExceptions (which is fine). What I'd like to do is display a simple "No articles/reviews/news exist" message instead, but since all three will throw the same exception, I'm unsure how to capture the right one and display the correct message based on the category which threw the exception.

I'm not sure if I should subclass Exception for these cases, and if I did, exactly where I'd throw them. Or, if there's a way to determine where the exception(s) came from so I could handle them properly.


Solution

  • I'm really confused at the results you're reporting. Entity Framework should return an empty IEnumerable when there are no results from a query. I've never seen it throw an ArgumentNullException in this case. Have you done anything weird with your Entity Framework templates?

    You should be able to step through your code and home in on exactly where the ArgumentNullException is coming from. (I have a sneaking suspicion it's happening outside of the method you posted).