How can I easily tell if two .NET EntityObjects collections contain any of the same objects?

Pages

have roles. Users have roles. A user can only view a page if he and she share one or more roles.

It works:

Dim Allow As Boolean = False
CurrentPage.Roles.Load()
For Each r As Role In CurrentPage.Roles
    r.Users.Load()
    For Each u As User In r.Users
        If u.Id = CurrentUser.Id Then
            Allow = True
            Exit For
        End If
    Next
    If Allow Then
        Exit For
    End If
Next

      

I don't want to use nested loops if I can instead do it in fewer lines of code with LINQ or a lambda expression.

This always returns False:

Dim Allow As Boolean = (CurrentPage.Roles.ToList.Intersect(CurrentUser.Roles.ToList).Count > 0)

      

I think this fails as roles are EntityObjects.

How can I match only role id values ​​to determine equality?

0


a source to share


1 answer


You will either have to use the second parameter of the Intersect method to provide your own custom IEqualityComparer, or you can try this. It looks funny, but it makes sense once you get it.

If CurrentPage.Roles.Any(Function(Role) Role.Users.Any(Function(User) User.Id = CurrentUser.Id)) Then
    'User has role
End If

      

Although this might not work if you actually load your users on every iteration. If you are loading from EntityFramework, I would recommend that you load them something like this:

CurrentPage.Roles.Include ("Users"). Any (...



Or I also created my own EnsureLoaded () extension that returns an object something like this:

If CurrentPage.Roles.Any(Function(a) a.Users.EnsureLoaded().Any(Function(b) b.Id = CurrentUser.Id)) Then

      

But if you are pushing db on every page request, make sure you check the profiler and make sure you only execute one request and not one request per role.

+2


a source







All Articles