linqravendbravendb4

RavenDb 4: Check if a string of an array of strings exists in different array of strings


I am trying to filter my activities based on user roles. The manager is only allowed to see the activities that contain the role Manager. See below for more information.

Data:

var user = new User
{
    Roles = [
        "Manager"
    ]   
}

var activities = new List<Activity>
{
    new Activity
    {
        Description = "My First Activity",
        Roles = [
            "Admin",
            "Manager"
        ]
    },  
    new Activity
    {
        Description = "My Second Activity",
        Roles = [
            "Admin"
        ]
    },  
    new Activity
    {
        Description = "My Third Activity",
        Roles = [
            "Manager",
            "Client"
        ]
    },
}

Query that filters the activity

 var filtered = await context.Query<Activity>()
                    .Where(x => x.Roles.Any(y => user.Roles.Contains(y)))
                    .ToListAsync();

Expected result of filtered:

[
    {
        new Activity
        {
            Description = "My First Activity",
            Roles = [
                "Admin",
                "Manager"
            ]
        }
        new Activity
        {
            Description = "My Third Activity",
            Roles = [
                "Manager",
                "Client"
            ]
        },
    }
]

Error from query

System.InvalidOperationException : Can't extract value from expression of type: Parameter

I am getting an error, so obviously I am doing something wrong. Is this the correct way or is there something better?


Solution

  • This requires RavenDB to do computation during query, try this, instead:

    .Where(x => x.Roles.In(user.Roles)) (might need to add a using statement for the In extension method, Raven.Client.Linq, IIRC).