Ø 简介
本文主要介绍 LINQ to SQL 中常见的异常,以及对应的解决办法。包括以下内容:
1. 左连接情况下,右表非空类型字段可能抛出异常
1. 左连接情况下,右表非空类型字段可能抛出异常
说明:UserInfo.CustomerId 关联 Customer.Id,为多对一的关系。但是 UserInfo.CustomerId 字段可能为 null, 所以运行以下语句将报错:
1) LINQ 语句
var datas1 = (from t1 in DataContext.UserInfoes
join t2 in DataContext.Customers on t1.CustomerId equals t2.Id into t12
from t3 in t12.DefaultIfEmpty()
where t1.id > 5000
select new
{
UserId = t1.id,
CustomerId1 = t1.CustomerId,
CustomerId2 = t3.Id
}).Take(3).ToArray();
2) 生成 SQL
SELECT
[Limit1].[C1] AS [C1],
[Limit1].[id] AS [id],
[Limit1].[CustomerId] AS [CustomerId],
[Limit1].[id1] AS [id1]
FROM ( SELECT TOP (3)
[Extent1].[id] AS [id],
[Extent1].[CustomerId] AS [CustomerId],
1 AS [C1],
[Extent2].[Id] AS [id1]
FROM [dbo].[UserInfo] AS [Extent1]
LEFT OUTER JOIN [dbo].[Customer] AS [Extent2] ON [Extent1].[CustomerId] = [Extent2].[Id]
WHERE [Extent1].[id] > 5000
) AS [Limit1]
3) 执行结果
4) 将抛出异常
System.InvalidOperationException:“到值类型“System.Int64”的强制转换失败,因为具体化值为 null。结果类型的泛型参数或查询必须使用可以为 null 的类型。”
5) 解决办法:
1. 分析:其实很简单,因为是左连接,左表记录不能与右表连接时,右表字段将以 null 返回。但是程序中是以 long 类型接收,不能为 null 值,所以就报错了。
2. 那我们是不是将非空类型(long)改为可空类型(Nullable<long>)就可以了?没错,我们只需要改写一行代码即可:
CustomerId2 = (long?)t3.Id