【问题标题】:How to return a list from a list of elements that have a list如何从具有列表的元素列表中返回列表
【发布时间】:2021-06-25 02:20:00
【问题描述】:

所以我有一个 API,我有一个饮食列表,里面有一个食谱列表。这是多对多的关系,我一直试图从特定饮食中获取食谱列表,但我只能获取整个饮食列表,包括他们的食谱列表,但我只想获取食谱列表。这是实际的代码。

    [HttpGet("[action]")]
    public async Task<IEnumerable<Diet>> GetRecipesFromDiet([FromRoute] int DietId)
    {
        var diet = _context.Diets.AsQueryable();
        diet = diet.Include(d => d.Recipes).AsNoTracking();
        List<Diet> _return = await diet.ToListAsync();
        return _return;
    }

我已经尝试使用 where 仅获取特定饮食,但它返回给我一个空列表,所以它不是一个选项。我什至在这里看到了一个有同样问题的人(Return list object with list object)的解决方案,但我试过了,但它给出了一个错误。这是我试过的代码。

    [HttpGet("[action]")]
    public async Task<IEnumerable<Diet>> GetRecipesFromDiet([FromRoute] int DietId)
    {
        var result = _context.Diets.Where(d => d.DietId == DietId).Select(d => new
        {
            Recipes = d.Recipes.Select(recipe => new
            {
                RecipeId = recipe.RecipeId,
                Name = recipe.Name,
                Description = recipe.Description,
                Preparation = recipe.Preparation,
                Ingredientes = recipe.Ingredients
            }).ToList(),
        });
        return (IEnumerable<Diet>)result;
    }

我必须添加显式转换,因为 Visual Studio 告诉我,我还尝试将方法的类型更改为 Task&lt;IEnumerable&lt;Recipe&gt;&gt; 也没有结果。它给出的错误就是这个。

System.InvalidCastException:无法转换类型为“Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable1[&lt;&gt;f__AnonymousType01[System.Collections.Generic.List1[&lt;&gt;f__AnonymousType15[System.Int32,System.String,System. String,System.String,System.String]]]]' 在 Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|10_0(ControllerActionInvoker 调用程序,任务 lastTask 中键入'System.Collections.Generic.IEnumerable1[NutricareApp.Entities.Diet]'. at NutricareApp.Web.Controllers.DietsController.GetRecipesFromDiet(Int32 DietId) in D:\Projects\C#\Server-Side-Software\NutricareApp.Web\Controllers\DietsController.cs:line 77 at lambda_method6(Closure , Object ) at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask1 actionResultValueTask) , 下一个状态, Scope 范围, 对象状态, Boolean isCompleted) 在 Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context) 在 Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state , Boolean& isCompleted) 在 Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync() --- 上一个位置的堆栈跟踪结束 --- 在 Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|19_0(Resourc Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker 调用程序,任务任务,IDisposable 范围)在 Microsoft.AspNetCore.Routing.EndpointMiddleware .g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext) at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware .Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider) at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context) HEADERS ======= Accept: text/plain Accept-Encoding: gzip, deflate, br Accept-Language: es -ES,es;q=0.9,en;q=0.8 连接:关闭 Cookie:Webstorm-1c66ffc5=ab57cd81-dd6b-4581-b4ce-e7c3216efe1b; Webstorm-1c670386=5cdc986c-d091-40b5-aafa-eba19ed04173 主机:localhost:44394 引用:https://localhost:44394/swagger/index.html 用户代理:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit /537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36 sec-ch-ua: "Not;A Brand";v="99", "Google Chrome";v="91", "Chromium"; v="91" sec-ch-ua-mobile: ?0 sec-fetch-site: 同源 sec-fetch-mode: cors sec-fetch-dest: 空

答案还提到要遵循 EF 约定,我的代码就是这样,所以我只需要遵循最后一部分,但我得到了这个错误,我不知道还能做什么。为了完全清楚,我只想要特定饮食的食谱列表,而不是带有食谱的饮食只是食谱。感谢您的帮助。

【问题讨论】:

    标签: c# .net asp.net-core entity-framework-core


    【解决方案1】:

    使用ToListAsyncDiets 拉出EF 查询。然后抓住他们的Recipes

    var diets = await _context.Diets
                              .Include(d => d.Recipes)
                              .Where(d => d.DietId == DietId)
                              .ToListAsync();
        
    return diets.Select(x => x.Recipes).ToList();
    

    【讨论】:

    • 它仍然给出“无法转换对象类型”的错误,即使是显式转换
    【解决方案2】:

    从你的加入表中选择可能更容易(显然我不知道你叫它什么,所以根据需要更改 Diets_To_Recipes):

    [HttpGet("[action]")]
    public async Task<IEnumerable<Recipe>> GetRecipesFromDiet([FromRoute] int DietId)
    {
        return _context.Diets_To_Recipes.Where(x => x.DietId == DietId)
               .Select(x => x.Recipe);
    }
    

    【讨论】:

    • 是的,我实际上没有连接表,因为如果表只有 pks,则不需要创建一个(EF 为您创建它,因此您不必创建它们),在我提供的链接中提到了
    • @DarkMage 我不知道 EF 是否可以将其转换为 SQL,但您可以尝试 Recipes.Where(x =&gt; x.Diets.Any(y =&gt; y.Id == DietId))
    • 我已经解决了这个问题,我的答案如下,感谢您的帮助。
    【解决方案3】:

    好的,经过一些尝试,我得到了解决方案

        [HttpGet("[action]/{DietId}")]
        public async Task<IEnumerable<RecipeModel>> GetRecipesFromDiet([FromRoute] int DietId)
        {
            var diets = await _context.Diets
                                    .Include(d => d.Recipes)
                                    .FirstOrDefaultAsync(d => d.DietId == DietId);
            var recipes = diets.Recipes.ToList();
            return recipes.Select(c => new RecipeModel
            {
                RecipeId = c.RecipeId,
                NutritionistId = c.NutritionistId,
                Name = c.Name,
                Ingredients = c.Ingredients,
                Description = c.Description,
                Preparation = c.Preparation
            });
        }
    

    我必须使用模型来“打印”食谱而不是创建循环(仅返回列表将导致“无法转换对象类型”,请记住这一点)。此外,它在第一次尝试中没有得到任何节食,因为我忘记将 id 添加到路线“[action]/{DietId}”。感谢您的帮助,我希望如果其他人遇到这个问题,这可以帮助他们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-14
      • 1970-01-01
      • 2021-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-15
      相关资源
      最近更新 更多