通过EFCORE中的联接表使用AutoMapper



我通过称为 Ingredient的加入表与 RecipeItem之间的众多关系:

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

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

应该看起来像这样:

CreateMap<Ingredient, ItemForDetailedDto>();
CreateMap<Ingredient,RecipeForDetailedDto>()
    .ForMember(dest=>dest.Name, opt=>opt.MapFrom(src=>src.Item?.Name));
var result = mapper.Map<ItemDetailedDto>(yourIngredientObject);

最后,这是有效的:

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

使用IngredientFordetailDto AS:

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

最新更新