我正在尝试编写一个允许搜索Ids列表的方法,但我希望允许列表是可选的。我见过List<string>的例子,但我在List<Guid>上遇到了麻烦。
在LinqPad中尝试这种方法,我得到消息:
无法创建一个空常量值,类型为'System.Collections.Generic.List`1[System.Guid,mscorlib、Version=4.0.0.0、Culture=neutral、PublicKeyToken=b77a5c561934e089]‘。在此上下文中只支持实体类型、枚举类型或基本类型。
下面是一个方法:
public static ICollection<Project> GetProjectsAllowed
(
    this IMkpContext db,
    Guid profileId,
    List<Guid> profOrgIds = null
)
{
    var projects = (from p in db.Project.Include(p => p.Proposals)
                    join po in db.ProfileOrganization on p.CreatedById equals po.ProfileId
                    where (profOrgIds == null || profOrgIds.Contains(po.OrganizationId))
                        && p.IsActive && po.IsActive
                    select p);
    return projects.ToList();
}更新:感谢您的评论,下面是我所做的:
public static ICollection<Project> GetProjectsAllowed
(
    this IMkpContext db,
    Guid profileId,
    List<Guid> profOrgIds = null,
    List<Guid> projectIds = null
)
{
    var projects = (from p in db.Project.Include(p => p.Proposals)
                    where p.IsActive
                    select p);
    if (profOrgIds != null && profOrgIds.Any())
    {
        var profileIds = db.ProfileOrganization
            .Where(po => po.IsActive && profOrgIds.Contains(po.OrganizationId))
            .Select(po => po.ProfileId);
        projects = projects.Where(p => profileIds.Contains(p.CreatedById));
    }
    if (projectIds != null && projectIds.Any())
        projects = projects.Where(proj => projectIds.Contains(proj.ProjectId));
    return projects.ToList();
}发布于 2016-03-11 16:03:29
这个问题与可选的List<Guid>参数无关。违规行位于LINQ查询中,是实体框架的一个限制:
where (profOrgIds == null...
本质上,Entity不知道如何将其转换为等效的SQL查询。
一种可能的解决方案是将条件转换为布尔值,EF应该能够处理该布尔值(诚然,这是未经测试的):
var listIsNull = profOrgIds == null;
var projects = (from p in db.Project.Include(p => p.Proposals)
                join po in db.ProfileOrganization on p.CreatedById equals po.ProfileId
                where (listIsNull || profOrgIds.Contains(po.OrganizationId))
                    && p.IsActive && po.IsActive
                select p);https://stackoverflow.com/questions/35944500
复制相似问题