How to query Entity Framework objects where select is a list

c# entity-framework-6 linq

Question

I am trying to do something simple, but I can't figure it out. Using EF6, I have 2 tables which are associated by an intermediate associative table, giving a many-to-many relationship:

2 associated tables Users and Families

I want to query all users who belong to a list of families. So I get an array of families:

var db = new MyProjectEntities(); 
User user = GetUserById((int)HttpContext.Current.Session["CurrentUserId"]);
var families = db.Users.Where(u => u.UserId == user.UserId).First().Families.ToArray();

Then I want to query all users belonging to these families:

var users = db.Users.Where(u => families.Contains(u.Families));

But I get this error:

Instance argument: cannot convert from 'Database.Family[]' to 'System.Linq.IQueryable>'

Thanks in advance.

1
1
7/16/2019 9:49:28 AM

Accepted Answer

You can use Any method:

var users = db.Users.Where(u => u.Families.Any(fam => families.Contains(fam))).AsEnumerable();

I think this is what you're searching for.

2
7/16/2019 9:48:20 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow