У меня есть отношения «многие ко многим» между 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; }
}
Есть ли способ сопоставить эту связь, чтобы отобразить список имен ингредиентов, который будет именем элемента?





Это должно выглядеть так:
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))
С IngredientForDetailedDto как:
public class IngredientForDetailedDto
{
public string Name { get; set; }
public int Quantity { get; set; }
public string QuantityType { get; set; }
}
Нулевая проверка не нужна, AM сделает это за вас.