【问题标题】:Using subquery value to filter parent result but still return all child items related to parent使用子查询值过滤父结果,但仍返回与父项相关的所有子项
【发布时间】:2021-09-14 18:08:15
【问题描述】:

我有许多电子邮件存储在数据库中,每封电子邮件都有一个子收件人。我正在尝试编写一个 LINQ 查询,其中我只返回具有收件人地址的电子邮件,例如某些提供的字符串,但如果返回父电子邮件,则仍然返回所有匹配或不匹配的收件人。我已经构建了这个有效的 SQL,但我的代码只过滤收件人而不是父电子邮件。

表格在 JSON 中包含的内容:

[
  {
    "email_id": "dcfe0dfc-e4ad-4fd3-b482-61ced67a19ec",
    "recipient": [
      {
        "email_address": "someemail@someplace.com"
      },
      {
        "email_address": "someotherAddress@example.com"
      }
    ]
  },
  {
    "email_id": "f53a7681-98f8-4385-b3d2-9e9af2560664",
    "recipient": [
      {
        "email_address": "someemail@someplace.com"
      },
      {
        "email_address": "a_newAddress@example.com"
      }
    ]
  },
  {
    "email_id": "f53a7681-98f8-4385-b3d2-9e9af2560664",
    "recipient": [
      {
        "email_address": "someAddress@email.com"
      },
      {
        "email_address": "a_newAddress@example.com"
      }
    ]
  }
]

SQL:

SELECT * FROM email e
RIGHT JOIN recipient r on e.email_id = r.email_id
WHERE r.email_id in (SELECT email_id 
                             from recipient WHERE email_address = 'someemail@someplace.com')
Order By e.create_date desc;

C# LINQ 语句

var query = _context.Email
                .IncludeFilter(x => x.Recipient.Where(r => string.IsNullOrEmpty(request.RecipientAddress) || 
                                                           EF.Functions.Like(r.EmailAddress, $"%{request.RecipientAddress}%"))).ToList();

预期输出:

[
    {
        "email_id": "dcfe0dfc-e4ad-4fd3-b482-61ced67a19ec",
        "recipient": [
          {
            "email_address": "someemail@someplace.com"
          },
          {
            "email_address": "someotherAddress@example.com"
          }
        ]
      },
      {
        "email_id": "f53a7681-98f8-4385-b3d2-9e9af2560664",
        "recipient": [
          {
            "email_address": "someemail@someplace.com"
          },
          {
            "email_address": "a_newAddress@example.com"
          }
        ]
      }
]

通过上述结果,我的结果按预期返回了所有电子邮件,但每个电子邮件中包含的收件人只是匹配的收件人,我希望它仍然返回所有收件人。任何帮助将不胜感激。

【问题讨论】:

  • 您能否提供示例输入和预期输出
  • 以json格式添加总数据示例和预期结果。

标签: c# postgresql linq .net-core entity-framework-core


【解决方案1】:

我想通了。它比我认为的要简单得多。

_context.email.Where(x => xstring.IsNullOrEmpty(request.RecipientAddress) ||
    x.Recipients.Any(y => 
        EF.Functions.Like(y.Email, $"%{request.RecipientAddress}%")))
    .Include(x => x.Recipients).OrderByDescending(x => x.CreateDate).ToList();

【讨论】:

  • 你应该也可以使用 Email.Contains() 代替 Like 函数。
猜你喜欢
  • 1970-01-01
  • 2021-09-15
  • 1970-01-01
  • 1970-01-01
  • 2022-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多