我正在尝试编写一个允许搜索 ID 列表的方法,但我希望该列表是可选的。我看过 List<string>
的例子但我遇到了 List<Guid>
的问题.
在 LinqPad 中尝试此方法,我收到消息:
Unable to create a null constant value of type 'System.Collections.Generic.List`1[[System.Guid, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'. Only entity types, enumeration types or primitive types are supported in this context.
方法如下:
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();
}
最佳答案
C# 方法可以接受空列表。您遇到的问题是 LINQ 查询本身。
您不能将对 profOrgIds
列表的 NULL 检查传递到与 Entity Framework 相关的 LINQ 查询中,因为 Entity Framework LINQ 提供程序(在此处使用,因为您正在对 EF 执行 LINQ 查询数据库上下文对象)无法将查询语法转换为等效的 T-SQL。
换句话说,摆脱
profOrgIds == null
从查询中,您应该没问题,但您需要在调用查询之前检查 profOrgIds 是否为空。
关于c# - C# 方法是否允许可空列表作为参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35944500/