部署 MVC3 Web 应用程序
大家好,我正在尝试将 ASP.NET MVC3 应用程序部署到我的网络服务器。这就是我所做的:
- 将所有项目上传到Web服务器
- 创建一个新的空数据库,运行SQL脚本来创建表和PK
- 修改web.config文件的connectionString属性以指向
- 添加的在线数据库
customErrors mode="On"
到 web.config
以下是我收到的错误:
抱歉,处理您的请求时发生错误。
System.InvalidOperationException:转换为值类型“Int32” 失败,因为具体化值为 null。要么是结果 类型的泛型参数或查询必须使用可为 null 的类型。
这是我请求的页面的代码:
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();
}
}
我猜这是因为表是空的,所以当我对数据库的查询返回 null 时,就会生成错误。
Good day all, I am trying to deploy my ASP.NET MVC3 app to my webserver. This is what I've done:
- Uploaded all the project to the web server
- Created a new empty DB, ran SQL scripts to create the tables and PKs
- Modified the web.config file's connectionString attribute to point to the online DB
- added
customErrors mode="On"
to web.config
Here 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果没有任何行,
Max()
会引发此异常。您可以通过将
game_id
转换为int?
来解决此问题,这将导致Max()
返回null
。您还可以调用
.DefaultIfEmpty()
。Max()
throws this exception if there aren't any rows.You can fix that by casting
game_id
to anint?
, which will causeMax()
to returnnull
.You could also call
.DefaultIfEmpty()
.