EF - 无法从System.Linq.IQueryable转换为System.Data.Objects.ObjectQuery

时间:2011-07-11 13:58:22

标签: linq entity-framework linq-to-entities

我需要在使用contentCategories方法时从allCategories中减去.Except的结果,但收到错误。

知道我做错了什么......非常感谢

Error   2   Argument 1: cannot convert from 'System.Linq.IQueryable<System.Data.Objects.DataClasses.EntityCollection<WebProject.DataAccess.DatabaseModels.CmsCategory>>' to 'System.Data.Objects.ObjectQuery<WebProject.DataAccess.DatabaseModels.CmsCategory>'

            int contentId = Int32.Parse(uxContentsListSelector.SelectedValue);
            var allCategories = from category in context.CmsCategories select category;
            var contentCategories = from content in context.CmsContents
                                          where content.ContentId == contentId
                                          select content.CmsCategories;
            var result = context.CmsCategories.Except(contentCategories);

2 个答案:

答案 0 :(得分:3)

您需要添加额外的from in子句才能获得展平列表。

var contentCategories = from content in context.CmsContents
                        from cat in content.CmsCategories
                        where content.ContentId == contentId
                        select cat;

然后我会将您的Except方法更改为Any方法

var result = context.CmsCategories.Where(cat => !contentCategories.Any(c => c.CategoryId == cat.CategoryId));

答案 1 :(得分:2)

那是因为你正在做的最后一次选择。此外,你的代码是高度还原的。让我们按步骤进行:

var allCategories = from category in context.CmsCategories select category;

您可以更简洁的方式重写相同的内容:

var allCategories = context.CmsCategories;

然后这是错误的:你选择了集合的查询而不是单个集合:

var contentCategories = from content in context.CmsContents
                                      where content.ContentId == contentId
                                      select content.CmsCategories;

正确的方法是:

var contentCategories = (from content in context.CmsContents
                                      where content.ContentId == contentId
                                      select content).First().CmsCategories;

这又是多余的,可以用更好的方式编写:

var contentCategories = context.CmsContents.First(c => c.ContentId == contentId).CmsCategories;

最后一句话是对的。