在单个方法中使用两个Linq查询

时间:2019-01-21 11:42:37

标签: c# linq api linq-query-syntax

如下面的代码所示,API将两次访问数据库以执行两次Linq查询。我只能通过一次点击数据库来执行下面显示的操作吗?

var IsMailIdAlreadyExist = _Context.UserProfile.Any(e => e.Email == myModelUserProfile.Email);

var IsUserNameAlreadyExist = _Context.UserProfile.Any(x => x.Username == myModelUserProfile.Username);

4 个答案:

答案 0 :(得分:4)

为了向数据库发出一个请求,您可以先仅过滤相关值,然后再次在查询结果中检查特定值:

var selection = _Context.UserProfile
    .Where(e => e.Email == myModelUserProfile.Email || e.Username == myModelUserProfile.Username)
    .ToList();

var IsMailIdAlreadyExist = selection.Any(x => x.Email == myModelUserProfile.Email);
var IsUserNameAlreadyExist = selection.Any(x => x.Username == myModelUserProfile.Username);

此处的.ToList()调用将对数据库执行一次查询并返回相关值

答案 1 :(得分:1)

开始

example.species <- data.frame (species = c("A","B","C","D","E"), habitat.specifity=NA)
example.species$habitat.specifity <- "g" # default value
example.species$habitat.specifity[example.species$species %in% c("B","C")] <- "s"
#   species habitat.specifity
# 1       A                 g
# 2       B                 s
# 3       C                 s
# 4       D                 g
# 5       E                 g

这将获得足够的信息,以单个查询最多不返回多于两行并且不检索未使用的信息来区分四种可能性(不匹配,电子邮件匹配,用户名匹配,都匹配)。因此,查询的大小可能会很小。

完成此操作

var matches = _Context
  .UserProfile
  .Where(e => e.Email == myModelUserProfile.Email)
  .Select(e => false)
  .Take(1)
  .Concat(
    _Context
      .UserProfile
      .Where(x => x.Username == myModelUserProfile.Username)
      .Select(e => true)
      .Take(1)
  ).ToList();

答案 2 :(得分:1)

可能有一点点hack,它可以按常量分组:

var presenceData = _Context.UserProfile.GroupBy(x => 0)
    .Select(g => new
    {
        IsMailIdAlreadyExist = g.Any(x => x.Email == myModelUserProfile.Email),
        IsUserNameAlreadyExist = g.Any(x => x.Username == myModelUserProfile.Username),
    }).First();

通过分组,您可以访问包含所有UserProfile的1个组,这些组可以在一个查询中随意访问。

不是那样,我会推荐它。该代码不是不言自明的,对我来说似乎是过早的优化。

答案 3 :(得分:0)

您可以使用ValueTuple和LINQ的.Aggregate()方法一行完成所有操作:

(IsMailIdAlreadyExist, IsUserNameAlreadyExist) = _context.UserProfile.Aggregate((Email:false, Username:false), (n, o) => (n.Email || (o.Email == myModelUserProfile.Email ? true : false), n.Username || (o.Username == myModelUserProfile.Username ? true : false)));