[英]How to utilize “IN” statement with Linq <> ASP.NET MVC <> C#
I am having struggles finding the best method to implement an IN statement.我很难找到实现 IN 语句的最佳方法。
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.我设置了一个存储 PartnerGUID 和 CustomerGUID 的 partnerLink 表,将关系结合起来。 The struggle I have is finding a method to allow a one to many relationship using an "IN" or "contains" option.我遇到的困难是找到一种方法来允许使用“IN”或“包含”选项建立一对多关系。
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));
You should not use ToList
when combining LINQ queries.组合 LINQ 查询时不应使用ToList
。 Everything should be IQueryable.一切都应该是 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
还可以考虑使用 Automapper 的ProjectTo
return _context.Stances
.Where(c => c.AccountGUID == userAccountID.CustomerGUID || partners.Contains(c.AccountGUID))
.ProjectTo<StancesDto>(configuration);
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)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.