c# - 使用 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>
”。存在显式转换(您是否缺少演员表?)
有任何想法吗?
解决方案
没有的原始代码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;
//...
推荐阅读
- python - 检测列表中的相同值
- android - 如何使用适用于 Android 的 Google Maps API 在 2 个标记之间绘制路线?
- css - 如何在我的 React 项目中使用 SCSS 全局变量和 mixin?
- reactjs - 使用 Oauth2、React、Node.js 和 Passport.js 通过 Google 登录按钮对用户进行身份验证的最佳做法是什么?
- ms-access - 表格字段为 4 位十进制,而原始数据仅为 2 位十进制
- azerothcore - 在 Visual Studio 中构建源代码时 .obj 文件中的错误
- mongodb - 在 kali linux 中安装 mongodb 时,我在 apt-get 中遇到错误
- php - 尽管我调用了补丁方法'@method('PATCH')',但修改按钮不起作用,我想显示文档但它没有出现
- javascript - javascript在循环后不起作用它在while和for中都是一样的
- matplotlib - 排序子图中的标签,使用 fig.add_axes 创建