db.Categories和List <category> </category>之间有什么区别吗?

时间:2012-01-15 10:37:55

标签: c# entity-framework-4.1

以下代码效果很好

IEnumerable<GroupedSelectListItem> groupList = db.Categories.Select(p => new GroupedSelectListItem()
{
     GroupKey = p.ParentCategory.Name,
     GroupName = p.ParentCategory.Name,
     Text = p.Name,
     Value = p.Name
});

以下代码生成对象引用未设置为实例错误

List<Category> orderedList = new List<Category>();
var rootList = db.Categories.Where(c => c.ParentCategoryId == null).ToList();
    foreach (var item in rootList)
    {
        orderedList.Add(item);
        if (item.SubCategories.Count != 0)
        {
            foreach (var subcat in item.SubCategories)
            {
                orderedList.Add(subcat);
                if (subcat.SubCategories.Count != 0)
                {
                    foreach (var subsubcat in subcat.SubCategories)
                    {
                        orderedList.Add(subsubcat);
                    }
                }
            }
        }
    }
IEnumerable<GroupedSelectListItem> groupList = orderedList.Select(p => new GroupedSelectListItem()
{
     GroupKey = p.ParentCategory.Name,
     GroupName = p.ParentCategory.Name,
     Text = p.Name,
     Value = p.Name
});

错误明细

  

第54行:IEnumerable groupList = orderedList.Select(p =&gt; new GroupedSelectListItem()

注意:对于某些等于null的记录,数据库中的类别表包含带有ParentCategoryId的元素

1 个答案:

答案 0 :(得分:2)

第一个代码片段使用具有自动合并功能的Linq-to-entities。如果p没有ParentCategory,它将在SQL级别上没有问题。第二个示例使用Linq-to-objects,其中不存在此类功能。在访问其属性之前,您必须手动检查ParentCategory属性是否已填充:

GroupKey = p.ParentCategory != null ? p.ParentCategory.Name : null 
相关问题