首页 > 解决方案 > 使用 EF Core 和条件 WHERE 子句从数据库读取行时出现问题

问题描述

我想在我的 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 子句,我就会得到这个异常:

错误 CS0266 无法将类型“ System.Linq.IQueryable<PropWorx.API.Models.Customer>”隐式转换为“ Microsoft.EntityFrameworkCore.DbSet<PropWorx.API.Models.Customer>”。存在显式转换(您是否缺少演员表?)

有任何想法吗?

标签: c#linqiqueryabledbset

解决方案


没有的原始代码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;

//...

推荐阅读