如何在Entity Framework Core中对查询结果集进行过滤?
解决方案
你只需要在EF Core查询时添加Where条件过滤archived列等于0的记录即可,步骤如下:
步骤1:引入Linq命名空间
在代码文件顶部添加引用:
using System.Linq;
步骤2:修改接口查询逻辑
调整caps/coils接口的查询代码,添加过滤条件,修改后完整代码如下:
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; using System.Collections.Generic; using System.Text.Json; using CAPSWebServer.CapsDataModels; using System.Linq; namespace Microsoft.AspNetCore.Builder { public static class CAPSServiceEndpoint { public static void MapWebService(this IEndpointRouteBuilder app) { app.MapGet("caps/coils", async context => { // 用GetRequiredService替代GetService,避免空引用异常 CapsDataContext data = context.RequestServices.GetRequiredService<CapsDataContext>(); // 添加Where条件过滤archived=0的记录,EF Core会自动生成对应的SQL过滤逻辑,在数据库层面完成筛选 var coils = data.Inventories.Where(i => i.archived == 0).ToList(); context.Response.ContentType = "application/json"; await context.Response.WriteAsync(JsonSerializer.Serialize<IEnumerable<Inventory>>(coils)); }); } } }
说明
- 过滤逻辑直接在数据库侧执行,不会把已完成退火的
archived=1的记录加载到内存,性能更优 - 如果你确认
archived列的类型是布尔类型,也可以直接写Where(i => !i.archived),效果一致
内容的提问来源于stack exchange,提问作者ROBERT RICHARDSON
相关产品推荐
相关产品推荐

