通过EFCore中的联接表使用Automapper

时间:2019-03-12 04:29:23

标签: entity-framework-core automapper

我通过名为Recipe的联接表在ItemIngredient之间建立了多对多关系:

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

有没有一种方法可以映射此关系以显示成分名称列表,即项目名称?

1 个答案:

答案 0 :(得分:0)

最后这是可行的:

    CreateMap<Ingredient, IngredientForDetailedDto>()
       .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Item.Name))

具有IngredientForDetailedDto为:

 public class IngredientForDetailedDto
    {
        public string Name { get; set; }
        public int Quantity { get; set; }
        public string QuantityType { get; set; }

    }