先看部门表设计和数据:
注意:Pid为父部门的Id号,如果是顶级部门则没有PId(pid为null)
如果要查询为NULL的PId,我们知道SQL语句应该是:
SELECT * FROM DEPART WHERE PID IS NULL
很多人用LinQ写成:
- int?pid=null;
- List<Depart>departList=context.Depart.Where(c=>c.PId==pid).ToList();
但是,结果departList.Count确为0.!怎么回事呢?查看LinQ生成的SQL语句才发现是=null判断,而不是is null判断。
- CompanyDataContextcontext=newCompanyDataContext();
- int?parentDepartId=null;
- IQueryable<Depart>query=null;
- //获取顶级部门的子部门数量
- query=fromdepartincontext.Depart
- wheredepart.PId==parentDepartId
- selectdepart;
- /*SELECT[t0].[Id],[t0].[Name],[t0].[PId]
- FROM[dbo].[Depart]AS[t0]
- WHERE[t0].[PId]=@p0*/
- List<Depart>departList=query.ToList();
- Console.WriteLine("count={0}",departList.Count);//count=0
- query=fromdepartincontext.Depart
- whereNullable<int>.Equals(depart.PId,parentDepartId)
- selectdepart;
- /*SELECT[t0].[Id],[t0].[Name],[t0].[PId]
- FROM[dbo].[Depart]AS[t0]
- WHERE[t0].[PId]ISNULL*/
- departList=query.ToList();
- Console.WriteLine("count={0}",departList.Count);//count=2
- parentDepartId=1;
- //获取1号部门的子部门数量
- query=fromdepartincontext.Depart
- wheredepart.PId==parentDepartId
- selectdepart;
- /*SELECT[t0].[Id],[t0].[Name],[t0].[PId]
- FROM[dbo].[Depart]AS[t0]
- WHERE[t0].[PId]=@p0*/
- departList=query.ToList();
- Console.WriteLine("count={0}",departList.Count);//count=0
- query=fromdepartincontext.Depart
- whereNullable<int>.Equals(depart.PId,parentDepartId)
- selectdepart;
- /*SELECT[t0].[Id],[t0].[Name],[t0].[PId]
- FROM[dbo].[Depart]AS[t0]
- WHERE([t0].[PId]ISNOTNULL)AND([t0].[PId]=@p0)*/
- departList=query.ToList();
- Console.WriteLine("count={0}",departList.Count);//count=2
为了演示,我采用了query查询,因为这样才能看到sql语句,现在我们看,如果要查询为null的结果,应该采用Nullable<T>.Equals()判断。注意第二个query,where Nullable<int>.Equals(depart.PId, parentDepartId)这样才能生成is null的sql,当parentDepartId不为null时,生成sql:WHERE ([t0].[PId] IS NOT NULL) AND ([t0].[PId] = @p0)。
所以:当数据库字段可以为空时,应采用Nullable<T>.Equals()判断,而不应该用==或Equals。