Error in MVC Linq

本文关键字:Linq MVC in Error | 更新日期: 2023-09-27 18:18:23

我在MVC中有Linq查询

obj_CCM.TeamName = (from c in db.Team_Master
                    where c.Id != TeamId
                    select new TypeTeam
                    {
                        TeamID = c.Id,
                        TeamName = c.TeamName
                    }
                   ).ToList();
Session["TeamId"] = obj_CCM.TeamName.Count > 0 ? Convert.ToInt32(obj_CCM.TeamName[0].TeamID) : -1;

I面朝下错误:

转换为值类型'Int32'失败,因为物化值为空。结果类型的泛型参数或查询必须使用可空类型。

Error in MVC Linq

我猜问题出在这一行:

TeamID = c.Id

在你的Team_Master表中,Id列必须是空的,所以它返回null,但TypeTeam中的TeamID属性被定义为int,不能持有空值。因此,您需要禁止您的Id列在数据库中接受空值或使TeamID属性为可空的整数。

public int? TeamID{ get; set; }

另外,作为旁注,您的查询返回List<TypeTeam>,但您将其存储在obj_CCM.TeamName中,这要么是打字错误,要么您可能已经定义了List<TypeTeam>类型的TeamName

先检查,如果

Session["TeamId"] != null
,然后进行转换