LINQ to SQL where in (lambda syntax)

Can someone help me with this please? I would just like where to. Here is the SQL that does what I want.

select ur.RoleID from UserRoles ur where ur.RoleID in (5, 15) 

And here is my attempt. The .IN () method does not exist, obviously just put my aggressive thoughts lol.

 int roleid; foreach (data r in dataList) { using (DataContext communityContext = new DataContext()) { roleid = communityContext.UserRoles .Where(x => x.UserID == r.ClientId && x.RoleID.IN(5, 15)) .Select(x => x.RoleID) .First(); } } 
+4
source share
3 answers

As you say, In does not exist, se .Contains() instead, if you have a list, in your case you can also use x.RoleId == 5 || x.RoleId == 15 x.RoleId == 5 || x.RoleId == 15

eg.

 var allowedRoles = new int[] { 5, 15 }; 

then in your where clause do the following:

 allowedRoles.Contains(x.RoleID) 
+8
source
 var setNumbers = new List<int>() { 5, 15}; communityContext.UserRoles.Where(x => x.UserID == r.ClientId) .Where(x => setNumbers.Contains( x.RoleID ) ) ... 

NTN

+1
source

I would rewrite it as ...

 int roleid; var allowedRoles = new[] {5, 15}; foreach (data r in dataList) { using (DataContext communityContext = new DataContext()) { roleid = communityContext.UserRoles .First(x=> x.UserID == r.ClientId && allowedRoles.Contains(x.RoleID)) .RoleID; } } 

Also, I'm not sure why you are creating a datacontext inside a loop. This seems wasteful since the datacontext is independent of the datalist.

0
source

Source: https://habr.com/ru/post/1387623/


All Articles