Steve Wolfe
Steve Wolfe

Reputation: 71

How to utilize "IN" statement with Linq <> ASP.NET MVC <> C#

I am having struggles finding the best method to implement an IN statement.

Currently I am using the below code in my controller to return a list of stances specific an individual customer account.

return _context.Stances
               .ToList()
               .Select(Mapper.Map<Stances, StancesDto>)
               .Where(c => c.AccountGUID == userAccountID.CustomerGUID);

I am in the process of creating a partner portal that would allow a Partner user to have access to many other customer accounts that each individual customer provides them access to.

I setup a partnerLink table that stores a PartnerGUID and a CustomerGUID, marrying the relationship. The struggle I have is finding a method to allow a one to many relationship using an "IN" or "contains" option.

What I am looking to do is something like this:

either load the list if it is just a customer "OR" if it is a partner account Load all customer stances in the partnerLink table.

 var partners = _context.PartnerLinks
                        .Where(user => user.PartnerGUID == userAccountID.CustomerGUID)
                        .Select(user => user.AccountGUID) // extract the emails from users
                        .ToList();

  return _context.Stances
                 .ToList()
                 .Select(Mapper.Map<Stances, StancesDto>)
                 .Where(c => c.AccountGUID == userAccountID.CustomerGUID || partners.Contains(c.AccountGUID));

Upvotes: 0

Views: 106

Answers (2)

Sam Ware
Sam Ware

Reputation: 127

I would think you could do it with a Union.

Sometime like:

return _context.Stances.Select(Mapper.Map<Stances, StancesDto>).Where(c => c.AccountGUID == userAccountID.CustomerGUID)
.Union(_context.Stances.Select(Mapper.Map<Stances, StancesDto>).Where(c => partners.Contains(c.AccountGUID)));

Upvotes: 0

Svyatoslav Danyliv
Svyatoslav Danyliv

Reputation: 27282

You should not use ToList when combining LINQ queries. Everything should be IQueryable.

var partners = _context.PartnerLinks
    .Where(user => user.PartnerGUID == userAccountID.CustomerGUID)
    .Select(user => user.AccountGUID);

return _context.Stances
    .Where(c => c.AccountGUID == userAccountID.CustomerGUID || partners.Contains(c.AccountGUID))
    .AsEnumerable()
    .Select(Mapper.Map<Stances, StancesDto>);

Also consider to use Automapper's ProjectTo

return _context.Stances
    .Where(c => c.AccountGUID == userAccountID.CustomerGUID || partners.Contains(c.AccountGUID))
    .ProjectTo<StancesDto>(configuration);

Upvotes: 2

Related Questions