我正在尝试编写一个允许搜索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 15:54:34
C#方法可以接受空列表。您遇到的问题是LINQ查询本身。
不能将对profOrgIds列表的空检查传递给实体框架相关的LINQ查询,因为实体框架LINQ提供程序(在这里使用,因为您正在对EF数据库上下文对象执行LINQ查询)无法将查询语法转换为等效的the。
换句话说,摆脱
profOrgIds == null
但是您需要在调用查询之前检查profOrgIds是空的。
发布于 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);发布于 2016-03-11 16:01:44
问题是空List的阻塞实体框架。
将此放在查询之前
profOrgIds = profOrgIds ?? new List<Guid>();和删除空检查,代码应该是固定的。
https://stackoverflow.com/questions/35944500
复制相似问题