首页 > 解决方案 > 通过 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; }
 }

有没有办法可以映射这种关系以显示成分名称列表,这将是项目名称?

标签: entity-framework-coreautomapper

解决方案


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; }

    }

推荐阅读