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

Problem reading rows from database using EF Core and conditional WHERE clauses

我想在我的 ASP .Net Core 3.0 Web API 中查询一个 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 子句:

var customers = _context.Customers.Where(c => c.IsDeleted == false);

但实际上我不想放入 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 子句时,我得到了这个异常:

Error CS0266 Cannot implicitly convert type 'System.Linq.IQueryable<PropWorx.API.Models.Customer>' to 'Microsoft.EntityFrameworkCore.DbSet<PropWorx.API.Models.Customer>'. An explicit conversion exists (are you missing a cast?)

有什么想法吗?

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

DbSet<Customer> customers = _context.Customers;

if (isActive.HasValue)
    customers = customers.Where(c => c.IsActive == isActive.Value);
    // Where returns IQueryable<Customer>, hence the error

在这种情况下,var 不利于您理解正在编写的代码。

使用 AsQueryable() 扩展来获得所需的行为

var customers = _context.Customers.AsQueryable(); //IQueryable<Customer>

//...

或明确说明使用的类型

IQueryable<Customer> customers = _context.Customers;

//...

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

Error CS0266 Cannot implicitly convert type
System.Linq.IQueryable<PropWorx.API.Models.Customer> to
Microsoft.EntityFrameworkCore.DbSet<PropWorx.API.Models.Customer>. An explicit conversion exists (are you missing a cast?)

每当您在给定行上遇到错误 "cannot implicitly convert Foo to Bar",例如

a = b;

表示操作数(ab)的类型不匹配(分别为BarFoo

解决方案始终是弄清楚这些类型中哪些与您期望的不同,然后弄清楚为什么这种类型与您期望的不同。

在你的例子中,两个操作数是 customerscustomers.Where(),这应该会提示你 Where() returns 与你的 customers变量。