C# 使用EF Core和条件WHERE子句从数据库中读取行时出现问题

C# 使用EF Core和条件WHERE子句从数据库中读取行时出现问题,c#,linq,iqueryable,dbset,C#,Linq,Iqueryable,Dbset,我想在我的ASP.NETCore3.0WebAPI中查询一个MySql数据库,并有条件地应用一些WHERE过滤器。因此,我的一个控制器操作中包含了这一点: [HttpGet] public async Task<IEnumerable<Customer>> GetCustomers([FromQuery] bool? isActive, [FromQuery] int? typeId, [FromQuery] bool? isProcessed) { var cu

我想在我的ASP.NETCore3.0WebAPI中查询一个MySql数据库,并有条件地应用一些WHERE过滤器。因此,我的一个控制器操作中包含了这一点:

[HttpGet]
public async Task<IEnumerable<Customer>> GetCustomers([FromQuery] bool? isActive, [FromQuery] int? typeId, [FromQuery] bool? isProcessed)
{
    var customers = _context.Customers.Where(c => c.IsDeleted == false);

    if (isActive.HasValue)
        customers = customers.Where(c => c.IsActive == isActive.Value);

    if (typeId.HasValue)
        customers = customers.Where(c => c.TypeId == typeId.Value);

    if (isProcessed.HasValue)
        customers = customers.Where(c => c.IsProcessed == isProcessed.Value);

    return await customers.ToListAsync();
}
但实际上我不想在这里加Where子句。我只想要这个:

[HttpGet]
public async Task<IEnumerable<Customer>> GetCustomers([FromQuery] bool? isActive, [FromQuery] int? typeId, [FromQuery] bool? isProcessed)
{
    var customers = _context.Customers;

    if (isActive.HasValue)
        customers = customers.Where(c => c.IsActive == isActive.Value);

    if (typeId.HasValue)
        customers = customers.Where(c => c.TypeId == typeId.Value);

    if (isProcessed.HasValue)
        customers = customers.Where(c => c.IsProcessed == isProcessed.Value);

    return await customers.ToListAsync();
}
但一旦我删除第一个Where条款,我就会得到一个例外:

错误CS0266无法隐式转换类型 “System.Linq.IQueryable”到 “Microsoft.EntityFrameworkCore.DbSet”。 存在显式转换。是否缺少强制转换

有什么想法吗?

没有var的原始代码看起来像

DbSet<Customer> customers = _context.Customers;

if (isActive.HasValue)
    customers = customers.Where(c => c.IsActive == isActive.Value);
    // Where returns IQueryable<Customer>, hence the error
或显式说明所使用的类型

IQueryable<Customer> customers = _context.Customers;

//...

给出的答案是正确的,我只想用一个一般提示来展开:

错误CS0266无法隐式转换类型 System.Linq.i能够 Microsoft.EntityFrameworkCore.DbSet。存在显式转换。是否缺少强制转换

无论何时出现错误,都不能隐式地将给定行上的Foo转换为Bar,例如

a = b;
这意味着操作数a、b分别具有不匹配的类型Bar、Foo

解决方法总是找出这些类型中的哪些与您期望的不同,然后找出为什么这种类型与您期望的不同


在您的情况下,这两个操作数是customers和customers。Where,这将提示您Where返回的类型与customers变量的类型不同。

使用AsQueryable扩展var customers=\u context.customers.asqueryablequikeryable customers=\u context.customers;与AsQueryable相比,它的优点是您将得到一个编译时检查,以确保右侧的内容实际上是IQueryable,例如,不是IEnumerable。这一点很好。谢谢你!下次遇到这个问题时,我会记住这一点。
IQueryable<Customer> customers = _context.Customers;

//...
a = b;