entity-framework-core - 通过 EFCore 中的连接表使用 Automapper
问题描述
Recipe
我在一个名为的Item
连接表之间建立了多对多的关系Ingredient
:
public class Recipe
{
public int RecipeId { get; set; }
public string Name { get; set; }
public ICollection<RecipeInstruction> RecipeInstructions { get; set; }
public ICollection<Ingredient> Ingredients { get; set; }
}
public class Ingredient
{
public Recipe Recipe { get; set; }
public int RecipeId { get; set; }
public Item Item { get; set; }
public int ItemId { get; set; }
public int Quantity { get; set; }
}
public class Item
{
public int ItemId { get; set; }
public string Name { get; set; }
public string Brand { get; set; }
public ICollection<Ingredient> Ingredients { get; set; }
}
我想通过这个 DTO 呈现数据:
public class RecipeForDetailedDto
{
public int RecipeId { get; set; }
public string Name { get; set; }
public ICollection<RecipeInstruction> RecipeInstructions { get; set; }
public ICollection<ItemForDetailedDto> Ingredients { get; set; }
}
有没有办法可以映射这种关系以显示成分名称列表,这将是项目名称?
解决方案
In the end this is what worked:
CreateMap<Ingredient, IngredientForDetailedDto>()
.ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Item.Name))
With IngredientForDetailedDto as:
public class IngredientForDetailedDto
{
public string Name { get; set; }
public int Quantity { get; set; }
public string QuantityType { get; set; }
}
推荐阅读
- python - 在 Windows 上安装 python selenium 包时遇到问题
- android - 当我尝试通过 recyclerView 中的 putExtra 发送对象时,我的应用程序不断崩溃
- angular - Angular 11 功能模块循环依赖
- hangfire - 为什么hangfire 作业会在多个服务器上运行?
- python - 对象没有属性“通道”
- javascript - onChange vs onInput?
- python - 如何交替使用 glob.glob("*PDF) 和 os.listdr("./directory")?
- c# - 用 ASP.NET MVC 5 中的值填充 PDF 字段
- r - 基于在没有 for() 循环的情况下递归调用列的先前元素,在 R 中生成一个新的变量/列?
- c# - 在 C# 中使用 Moq 模拟接口实现