RoLYroLLs
RoLYroLLs

Reputation: 3215

Proper LINQ Expression

I've been trying to search Google but to no avail. It feels like it's been asked before, but maybe I'm not Googling what I think I need correctly.

I want to get a collection of Object who's ICollection<T>'s Id property is a value.

Which way should I write this Linq Expressions?

For example:

public class User {
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<Role> Roles { get; set; }
}

public class UserRole {
    public int UserId { get; set; }
    public int RoleId { get; set; }
}

If I know a RoleId, how do I get all the User's? The following seems like it's correct and it does give me what I need:

Example 1

var roleId = 1;
var users = db.UserRoles.SingleOrDefault(r => r.RoleId == roleId).Roles;

but, is it possible to get the same results in reverse? For example, I've tried this:

Example 2

var roleId = 1;
var users = db.Users.Where(u => u.UserRoles.Where(r => r.RoleId == roleId)).Users;

I get a message saying Cannot convert type UserRole to bool.

I ask because I'm using to thinking like this: "Get `Object-X where it's Object-Y has this value".

Maybe I'm making this confusing, but I hope someone helps clear it up.

Upvotes: 0

Views: 74

Answers (1)

koryakinp
koryakinp

Reputation: 4125

If I know a RoleId, how do I get all the User's?

Assuming Role class has a RoleId property you can do something like that:

var roleId = 1;
var users = db.Users.Where(q => q.Roles.Any(w => w.RoleId == roleId));

Upvotes: 5

Related Questions