Linq DbContext - 如果其他列表包含值,则过滤

时间:2014-02-12 12:21:29

标签: linq entity-framework dbcontext

只有当另一个列表中存在值时,我才需要Linq查询才能在结果中包含项目。我一直在这里和MSDN文档中查看,但是无法正确使用语法。

我有一个用户角色列表:

var userRoles = _identityManager.GetUserRoles(userId);
var roles = userRoles.Select(role => role.RoleId).ToList();

我希望针对DbContext的查询仅在其AccessRole位于角色列表中时才包含项目:

documents = context.ClientDocuments
.Where(d => d.ClientID == clientId)
//&& roles.contains d.AccessRole // pseudo code
.OrderByDescending(d => d.DateCreated)
.Select(
    doc => new ClientDocumentDto()
    {
        DocumentID = doc.ClientDocumentID,
        Name = doc.Name,
        Project = doc.Project,
        DocumentType = doc.DocumentType,
        DateCreated = doc.DateCreated,
        AccessRole = doc.AccessRole
    });

1 个答案:

答案 0 :(得分:1)

如何在Where子句中指定条件?

documents = context.ClientDocuments
.Where(d => d.ClientID == clientId && roles.Contains(d.AccessRole))

.OrderByDescending(d => d.DateCreated)
.Select(
    doc => new ClientDocumentDto()
    {
        DocumentID = doc.ClientDocumentID,
        Name = doc.Name,
        Project = doc.Project,
        DocumentType = doc.DocumentType,
        DateCreated = doc.DateCreated,
        AccessRole = doc.AccessRole
    });