【问题标题】:Check if queryable is null before assigning a list在分配列表之前检查可查询是否为空
【发布时间】:2021-05-13 04:00:43
【问题描述】:

我有一个有效的查询,但大部分空间仅用于一次检查以考虑 IQueryable 是否为空,并且基于整个查询重复。您能否帮我想出一个可能不需要此检查的实现。

IQueryable<Customer> customers = null;
if (customers != null)
    customers.Concat(_context.Developers.Include(s => s.Project)
        .ThenInclude(op => op.Customer)
        .Where(developer=> developer.DeveloperId == userId).Select(developer => developer.Project.Customer));
else 
    customers = _context.Developers.Include(s => s.Project)
        .ThenInclude(op => op.Customer)
        .Where(developer=> developer.DeveloperId == userId).Select(developer => developer.Project.Customer));

我已经尝试将客户初始化为

customers = Enumerable.Empty<T>().AsQueryable();

这导致另一个异常:源 IQueryable 的提供程序没有实现 IAsyncQueryProvider。

【问题讨论】:

  • 您是否在 userId 值列表上循环?
  • 我有一个开发者模型,基本上是一个中间表,其中包含一个项目列表和一个开发者 ID。与该开发人员关联的项目是该开发人员被分配工作的项目。
  • 我需要提取位于项目记录中的客户记录
  • 不,userId是单数字符串值

标签: entity-framework linq asp.net-core-webapi


【解决方案1】:

您可以将额外的客户查询“保存”在变量中并使用它:

var extraCustomersQuery = _context.Developers.Include(s => s.Project)
                            .ThenInclude(op => op.Customer)
                            .Where(developer=> developer.DeveloperId == userId).Select(developer => developer.Project.Customer));

customers = customers?.Concat(extraCustomersQuery) ?? extraCustomersQuery;

如果您只是在一组用户 ID 上循环,您可以只创建一个带有 Contains 的查询,而无需 Concating 多个(假设 userIds 是用户 ID 的集合),如果您只需要Customer 没有包含的查询应该可以正常工作:

var customers = _context.Developers
    .Where(developer => userIds.Contains(developer.DeveloperId))
    .Select(developer => developer.Project.Customer));

【讨论】:

  • 只是出于好奇,是什么让您认为 userId 是一个集合?鉴于 userId 是单个字符串,请同时提出对查询的任何改进建议
  • @RidaM 很乐意提供帮助。我没有假设userId 是一个集合,我假设userIds 是一个集合,因为整个结构看起来就像您正在循环连接查询。显然还有其他可能性,但如果没有周围的代码,很难提出任何建议。
  • public class Developer { public int Id { get; set; } public Project Project{ get; set; } public int ProjectId { get; set; } public string DeveloperId { get; set; } public string DeveloperName {get; set;} } public class Project { // among many other attributed public int CustomerId { get; set; } public Customer Customer { get; set; } public ICollection&lt;Developer&gt; Developers { get; set; } } 对格式问题表示歉意。希望上面的类结构有帮助
  • @RidaM 我在谈论更多关于有问题的代码。
  • 这部分代码没有其他代码。我在 mediatR 处理程序中有此代码,它接收开发人员的 userId,我必须返回与该开发人员关联的客户列表
猜你喜欢
  • 1970-01-01
  • 2020-03-04
  • 1970-01-01
  • 1970-01-01
  • 2019-03-06
  • 1970-01-01
  • 2010-11-04
  • 2010-10-09
  • 1970-01-01
相关资源
最近更新 更多