Good day all, I am trying to deploy my ASP.NET MVC3 app to my webserver. This is what I've done:
customErrors mode="On"
to web.configHere is what error I get:
Sorry, an error occurred while processing your request.
System.InvalidOperationException: The cast to value type 'Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.
Here is my code for the page I am requesting:
public ActionResult Index()
{
ViewBag.Message = "Last game is #" + this.getLastGameId();
return View();
}
public int getLastGameId()
{
using (HockeyStatsEntities context = new HockeyStatsEntities())
{
return context.Dim_Game.Select(g => g.Game_id).Max();
}
}
I am guessing this is because the tables are empty so that when my query to the db is returning null, that generates the error.
Max()
throws this exception if there aren't any rows.
You can fix that by casting game_id
to an int?
, which will cause Max()
to return null
.
You could also call .DefaultIfEmpty()
.