Fab*_*uez 0 c# linq iqueryable dbset
我想在我的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();
}
Run Code Online (Sandbox Code Playgroud)
这完美地工作了,因为在第一行中有一个Where子句:
var customers = _context.Customers.Where(c => c.IsDeleted == false);
Run Code Online (Sandbox Code Playgroud)
但实际上我不想放入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();
}
Run Code Online (Sandbox Code Playgroud)
但是,一旦我删除了第一个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 IQuaryable<Customer>, hence the error
Run Code Online (Sandbox Code Playgroud)
在这种情况下,var您可能无法理解正在编写的代码。
使用AsQueryable()扩展名获得所需的行为
var customers = _context.Customers.AsQueryable(); //IQueryable<Customer>
//...
Run Code Online (Sandbox Code Playgroud)
或明确说明使用的类型
IQueryable<Customer> customers = _context.Customers;
//...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37 次 |
| 最近记录: |