使用 EFCore 在 ASp.net Core 中过滤数据

Filtering Data in ASp.net Core using EFCore

我确实有一个 Web api 项目,它使用 asp.net 核心和 SQL 服务器和 EFCore5。我有一个患者实体模型,它有一个 diagnosticID 列,我想根据这个列 Id (GUID) 过滤患者,我该如何实现这个场景: 1- 当客户端不发送任何 diagnosticId (null) 时,我想 return 所有患者。 2-当客户端发送特定的 diagnosticId 时,我需要有具有该特定 diagnosticId 的患者。

基本上,null 必须转换 All,其余转换为发送的 Id。我可以用 If 和 Else 来实现这个

    If(diagnosticId == null ) 
    { 
    //Query to return all the patients 
    } else {
    //Query to return patients with specific Id 
    }

但我认为应该有更好、更专业的方法来做到这一点。 谁能帮我解决这个问题?

LINQ 是可组合的。您可以这样做以避免重复基本查询:

var query = context.Patients;

if (diagnosticId != null)
{
    query = query.Where(p => p.DiagnosticId == diagnosticId);
}