日期:2014-05-20  浏览次数:20790 次

Linq查询结果中包含null的问题

CREATE TABLE [dbo].[ConsumeCategory] (
    [ConsumeCategoryID]   INT           IDENTITY (1, 1) NOT NULL,
    [ConsumeCategoryName] NVARCHAR (10) NOT NULL,
    [BusinessCategoryID]  INT           NULL)

上面表中BusinessCategoryID可能为null

ConsumeCategoryManager ccm=new ConsumeCategoryManager();
var query =
   (from cc in ccm.GetAllConsumeCategory()
    where cc.ConsumeCategoryID == Convert.ToInt32(cbb_consumeCategory.SelectedValue)
    select cc);
if (query.Single().BusinessCategoryID==null)
{}

GetAllConsumeCategory()方法返回ConsumeCategory所有数据,我的想法是通过ConsumeCategoryID来判断表中对应的BusinessCategoryID是否为null
执行到if()的时候总是报错
无法将类型为“<>f__AnonymousType0`2[System.Int32,System.String]”的对象强制转换为类型“System.IConvertible”。
------解决方案--------------------
var query = ccm.GetAllConsumeCategory().SingleOrDefault(cc=> cc.ConsumeCategoryID == Convert.ToInt32(cbb_consumeCategory.SelectedValue));

if (query!=null &&Nullable<int>.Equals(query.BusinessCategoryID,null) ){}