简体   繁体   中英

Having multiple Ids on linq-sql join query in c#

I have a linq-to-sql query that fetches records.

First of all, I have a variable that can hold an Id or multiple Ids.

var consumerId = _context.Consumers.Where(x => x.UsrDefault.Equals("True"));
// This can return one or an array of Ids. 

Then, I have a linq-to-sql query as follows:

var query = (from users in _context.Users 
            join consumers in _context.Consumers 
            on usersId equals consumerId 
            select new UserConsumerDto 
            {
             FirstName = users.FirstName, 
             LastName = users.LastName
            }).ToList()

My question is that when I have multiple consumerId , how can I perform this linq-to-sql query ? I want to avoid any foreach loop.

Can someone please advise ?

Contains is the method to be used here or Any() .

See the code snippet below:

var query = (from users in _context.Users 
            join consumers in _context.Consumers 
            on users.usersId equals consumers.consumerId 
            where consumerId.Contains(consumers.consumerId)
            select new UserConsumerDto 
            {
             FirstName = users.FirstName, 
             LastName = users.LastName
            }).ToList()

for any :

where consumerId.Any(id => id == consumers.consumerId)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM