我想在我的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'隐式转换为'Microsoft.EntityFrameworkCore.DbSet'。存在显式转换(您是否缺少演员表?)
有什么想法吗?
没有var
的原始代码看起来像
DbSet<Customer> customers = _context.Customers;
if (isActive.HasValue)
customers = customers.Where(c => c.IsActive == isActive.Value);
//Where returns IQuaryable<Customer>, hence the error
这是var
在帮助您理解正在编写的代码的情况。
使用AsQueryable()
扩展名获得所需的行为
IQueryable<Customer> customers = _context.Customers.AsQueryable();
//...