linq query无法在集合中创建常量值集合

时间:2013-06-18 19:46:54

标签: linq entity-framework

我试图获取标签为publid(DisplayFor = false)或具有所需权限的文章(DisplayFor = true;而article.groups包含授予的组;)和(GroupId = Guid.Empty为每个注册用户) :

List<Group> groups = new UserBiz().Groups(AchaAuth.CurrentUserId);
var result = from HeadsupArticle article in ctx.HeadsupArticles
                             where article.GroupId == item.GroupId &&
                                   article.Active &&
                                   (!article.DisplayFor || (article.DisplayFor && article.Groups.Any(g =>
                                    g.GroupId == Guid.Empty ||
                                    groups.Select(i => i.GroupId).Contains(g.GroupId)
                                   )))
                             select article;

问题是

Unable to create a constant value of type 'Achasoft.AchaCms.Models.Group'. Only primitive types or enumeration types are supported in this context.

我需要一个合适的linq查询,所以我不需要选择1000条记录才能从中获取10条记录

1 个答案:

答案 0 :(得分:0)

试试这个。这将从LINQ查询中删除组列表,但如果您的groupId是Guid,并且用户可以有多个组,您将向查询发送一个非常大的guid列表。

List<Group> groups = new UserBiz().Groups(AchaAuth.CurrentUserId);
var groupsIds = groups.Select(i => i.GroupId).ToList();
var result = from HeadsupArticle article in ctx.HeadsupArticles
                             where article.GroupId == item.GroupId &&
                                   article.Active &&
                                   (!article.DisplayFor || (article.DisplayFor && article.Groups.Any(g =>
                                    g.GroupId == Guid.Empty ||
                                    groupsIds.Contains(g.GroupId)
                                   )))
                             select article;

当groupIds部分包含在查询中时。 EF试图将Enumerable转换为SQL Query,这是不可能的。通过提取和强制ToList()(ToList是重要部分),您强制EF将列表转换为看起来像

的SQL查询
 WHERE g.GroupId IN ('guid1', 'guid2', ... 'guidN')
相关问题