【发布时间】:2018-01-24 13:28:26
【问题描述】:
我有以下编译的 Linq 查询:
public static readonly Func<DBContext, Models.User, Type, ObjectType, int?, UserNotification> GetUnreadNotificationID =
CompiledQuery.Compile((DBContext db, Models.User forUser, Type notificationType, ObjectType forObjectType, int? forObjectID) =>
db.UserNotifications.FirstOrDefault(c =>
c.ForUserID == forUser.ID
&& c.ForObjectTypeID == (short)forObjectType
&& c.ForObjectID == forObjectID
&& c.TypeID == (byte)notificationType
&& c.Date > forUser.NotificationsLastRead.Date));
注意参数int? forObjectID。
在查询分析器中,执行的 SQL 语句示例如下:
exec sp_executesql N'SELECT TOP (1)
[t0].[ID], [t0].[TypeID], [t0].[ForUserID], [t0].[Date], [t0].[ForObjectTypeID], [t0].[ForObjectID], [t0].[Count]
FROM
[dbo].[UserNotifications] AS [t0]
WHERE
([t0].[ForUserID] = @p0)
AND ([t0].[ForObjectTypeID] = @p1)
AND ([t0].[ForObjectID] = @p2)
AND ([t0].[TypeID] = @p3)
AND ([t0].[Date] > @p4)',
N'@p0 int,@p1 int,@p2 int,@p3 int,@p4 datetime',@p0=77812,@p1=5,@p2=NULL,@p3=4,@p4='2018-01-24 13:18:44.107'
当forObjectID 为null 时,查询不会返回预期的记录。如果我改变:
AND ([t0].[ForObjectID] = @p2)
收件人:
AND ([t0].[ForObjectID] IS NULL)
它确实返回了正确的结果。
- 为什么 null 没有按我期望的方式处理?
- 有简单的解决方法吗? (我可以将表格转换为不接受该字段的空值并默认为 0 但感觉很恶心)
【问题讨论】:
标签: c# linq-to-sql int nullable isnull