如果列表为空,linq Take返回空异常

时间:2019-02-08 03:29:26

标签: c# asp.net-mvc entity-framework linq

我面临的一个挑战是,我正在使用LINQ通过Take方法获取前5条记录,但是如果列表为空,则抛出以下异常:

  

无法将类型'System.Nullable`1 [[System.Int64,mscorlib,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089]]强制转换为类型'System.Object'。 LINQ to Entities仅支持强制转换EDM基本类型或枚举类型。

所以请指导我如何解决它。

下面我提供了示例代码

openTickets_Result = (from tic in db.Tickets1
                      join com in db.Company on tic.company_id equals com.id
                      join bra in db.Branch on tic.branch_id equals bra.id
                      join use in db.Users on tic.assinged_to equals use.Id
                     where companyIds.Any(x => x.Equals((long)tic.company_id)) 
                     && branchIds.Any(x => x.Equals(tic.branch_id))
                     && tic.status == "Open"
                     && tic.priority == "High"
                      select new Details {
                           Assinged_To = use.FullName,
                           Company_Name = com.name,
                           Branch_Name = bra.branch_name,
                           ticketName=tic.Name
                      }).OrderBy(x => x.Create_Date).Take(5).ToList();

如果列表有时为empty/null,则Take方法将给出异常。

1 个答案:

答案 0 :(得分:0)

因为 branchIds 是长的非空类型, x => x.Equals(tic.branch_id),此处的tic.branch_id是长的空类型,因此需要进行类型转换它

openTickets_Result = (from tic in db.Tickets1
                      join com in db.Company on tic.company_id equals com.id
                      join bra in db.Branch on tic.branch_id equals bra.id
                      join use in db.Users on tic.assinged_to equals use.Id
                      where companyIds.Any(x => x.Equals((long)tic.company_id)) && branchIds.Any(x => x.Equals((long)tic.branch_id)) && tic.status == "Open" && tic.priority == "High"
                      select new LiveTickets
                      {
                          Assinged_To = use.FullName,
                          Company_Name = com.name,
                          Branch_Name = bra.branch_name,
                          ticketName=tic.Name
                      }).OrderBy(x => x.Create_Date).Take(5).ToList();
  

无论如何,感谢大家的支持。