首页 > 解决方案 > 如何在 Entity Framework Core 中过滤结果集?

问题描述

我有一个用 Entity Framework Core 编写的非常小的 Web 服务,它返回已经、正在或将要退火的线圈列表。我不在乎那些已经退火的。如何将过滤器过滤掉完成的过滤器?

Inventory表包括一列archived。我想查询archived列包含零的那些行。我怎么做?

查询正在IEndpointRouteBuilder接口上的扩展方法中执行:

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using System.Collections.Generic;
using System.Text.Json;
using CAPSWebServer.CapsDataModels;

namespace Microsoft.AspNetCore.Builder
{
    public static class CAPSServiceEndpoint
    {
        public static void MapWebService(this IEndpointRouteBuilder app)
        {
            app.MapGet("caps/coils", async context =>
            {
                CapsDataContext data = context.RequestServices.GetService<CapsDataContext>();
                var coils = data.Inventories;                
                context.Response.ContentType = "application/json";
                
                await context.Response.WriteAsync(JsonSerializer.Serialize<IEnumerable<Inventory>>(data.Inventories));
            });
        }
    }
}

标签: entity-framework-core

解决方案


假设archived是一个布尔值,你应该能够做到:

await data.Inventories.Where(inventory => !inventory.Archived).ToListAsync();.

你很可能需要一个usingforSystem.LinqMicrosoft.EntityFrameworkCore


推荐阅读