【问题标题】:How can I map correctly a model in a model in EF Core 5?如何在 EF Core 5 的模型中正确映射模型?
【发布时间】:2021-03-05 10:41:13
【问题描述】:

我有一个如下所示的 Recipe 对象(所有代码都是简化示例):

public class Recipe
{
    public int Id { get; set; }

    [Required]
    [StringLength(4000)]
    public string Description { get; set; }

    [Required]
    public virtual ICollection<RecipeIngredient> Ingredients { get; set; } = new List<RecipeIngredient>();
}

如您所见,我的 Recipe 对象有一个如下所示的 RecipeIngredient 列表:

public class RecipeIngredient
{
    public int Id { get; set; }

    public int IngredientId { get; set; }
    public Ingredient Ingredient { get; set; }

    public int Quantity { get; set; }
}

我需要这个新的 RecipeIngredient 模型来跟踪配方中每种成分的需要量。

问题是,我有一个控制器,我尝试在这样的列表中返回每个食谱:

// GET: api/Recipes
[HttpGet]
public async Task<ActionResult<IEnumerable<Recipe>>> GetRecipes()
{
    return await _context.Recipes.Include(m => m.Ingredients).ToListAsync();
    //return await _context.Recipes.ToListAsync();
}

如您所见,有一个注释部分,其中我没有在模型中包含成分列表(但我也必须得到它们)并且它的工作原理很明显,这个包含部分是错误的。

你有什么想法吗?我不确定如何映射它,或者引入新模型是否适合解决我的问题

【问题讨论】:

  • 您只包括RecipeIngredient,而不包括成分。要包含 RecipeIngredient 和 Ingredient,您需要 _context.Recipes.Include(r =&gt; r.Ingredients).ThenInclude(ri =&gt; ri.Ingredient)...。但我会在你的 API 中添加一个合适的模型。
  • 从 EF Core 5 开始,您可以在没有关系实体的情况下设置多对多关系:Official documentation
  • "很明显,这个包含部分是错误的" - 可能是,但只有在我们知道您所期望的结果时我们才能知道?您的 JSON 结果应该是什么样子?
  • @atiyar 所以我有一个 Recipe 对象,它必须存储所需数量的成分。所以我创建了一个 RecipeIngredient 模型,其中我有一个带有它所属食谱的成分。所以我想得到我所有的食谱和所有需要的原料。所以它看起来像这样:`recipe:{"id": 0, "description:"...", "Ingredients": [RecipeIngredient objects]} ` 希望它能清除我需要的东西

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


【解决方案1】:

如果您期望的结果应该是这样的(正如您在评论中提到的)-

recipe:{"id": 0, "description:"...", "Ingredients": [RecipeIngredient objects]}

那么你的查询应该看起来像 -

await _context.Recipes
        .Include(p => p.Ingredients)
        .ThenInclude(p => p.Ingredient)
        .ToList();

【讨论】:

    猜你喜欢
    • 2019-01-30
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-30
    • 1970-01-01
    相关资源
    最近更新 更多