简体   繁体   English

使用 ef 核心中的 OR 条件基于所有可选参数的动态查询

[英]Dynamic Query based on all optional parameters using an OR condition in ef core

I'm not sure if I'm barking up the wrong tree but I wanted to create a function to check if an account exists based on all optional parameters so it can be used to pull data depending on whatever you'd like to check on.我不确定我是不是找错了树,但我想创建一个 function 来根据所有可选参数检查帐户是否存在,以便它可以用于根据您想要检查的任何内容提取数据.

Basically the query should be: where loginName = p1 or loginName = p2 or loginName = p3 but with the paramters all being optional, however at least one will be provided.基本上,查询应该是:其中 loginName = p1 或 loginName = p2 或 loginName = p3 但参数都是可选的,但至少会提供一个。

This is what I tried so far:这是我到目前为止所尝试的:

 public async Task<bool> CheckAccountExistsAsync(string loginName = "", string authenticatorId = "", string eId = "")
    {
      if (string.IsNullOrWhiteSpace(loginName) && string.IsNullOrWhiteSpace(authenticatorId) && string.IsNullOrWhiteSpace(eId))
        throw new InvalidOperationException("You must pass at least one parameter");

      return await _context.Accounts.AnyAsync(a =>
          (string.IsNullOrWhiteSpace(loginName) || a.LoginName == loginName)
          || (string.IsNullOrWhiteSpace(authenticatorId) || a.AuthenticatorId == authenticatorId)
          || (string.IsNullOrWhiteSpace(eId) || a.EmployeeId == eId));
    }

Problem with this approach is that if I just pass the loginName, then the query is as follows with the condition completely omitted.:这种方法的问题是,如果我只传递登录名,那么查询如下,条件完全省略:

      SELECT CASE
          WHEN EXISTS (
              SELECT 1
              FROM [Accounts] AS [a]) THEN CAST(1 AS bit)
          ELSE CAST(0 AS bit)
      END

I'm sure I'm missing something, is there a better approach?我确定我错过了一些东西,有没有更好的方法?

What you are using is applicable for optional and expressions, eg您正在使用的适用于可选and表达式,例如

return await _context.Accounts.AnyAsync(a =>
    (string.IsNullOrWhiteSpace(loginName) || a.LoginName == loginName)
    && (string.IsNullOrWhiteSpace(authenticatorId) || a.AuthenticatorId == authenticatorId)
    && (string.IsNullOrWhiteSpace(eId) || a.EmployeeId == eId));

For optional or you have to use optional and sub conditions and add additional check for all optional parameters missing, eg对于可选的or您必须使用可选and子条件,并添加对所有可选参数缺失的附加检查,例如

return await _context.Accounts.AnyAsync(a =>
    (string.IsNullOrWhiteSpace(loginName)
    && string.IsNullOrWhiteSpace(authenticatorId)
    && string.IsNullOrWhiteSpace(eId))
    || (!string.IsNullOrWhiteSpace(loginName) && a.LoginName == loginName)
    || (!string.IsNullOrWhiteSpace(authenticatorId) && a.AuthenticatorId == authenticatorId)
    || (!string.IsNullOrWhiteSpace(eId) && a.EmployeeId == eId));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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