带有子列表属性映射的自动映射问题

时间:2016-09-11 15:55:57

标签: c# .net automapper automapper-5

我有以下模特

模型

public class Dish
{
    [Required]
    public Int64 ID { get; set; }
    [Required]
    public string Name { get; set; }
    [Required]
    public string Description { get; set; }
    [Required]
    public double Price { get; set; }
    [Required]
    public DateTime From { get; set; }
    [Required]
    public DateTime To { get; set; }
    [Required]
    public bool IsAvailable { get; set; }
    [Required]
    public string MealImage { get; set; }
    [Required]
    public List<Ingredients> Ingredients { get; set; }
}


public class Ingredients
{
    [Required]
    public Int64 ID { get; set; }
    [Required]
    public string Name { get; set; }
    [Required]
    public int Quantity { get; set; }
    [Required]
    public Int64 Dish_ID { get; set; }
    [ForeignKey("Dish_ID")]
    public virtual Dish Dish { get; set; }
}

以下是他们的 ViewModel

 public class DishViewModel
{
    public Int64 ID { get; set; }
    [Required]
    public string Name { get; set; }
    [Required]
    public string Description { get; set; }
    [Required]
    public double Price { get; set; }
    [Required]
    public DateTime From { get; set; }
    [Required]
    public DateTime To { get; set; }
    public bool IsAvailable { get; set; }
    public string MealImage { get; set; }
    [Required]
    public string IngredientsData { get; set; }

    public List<IngredientsViewModel> Ingredients { get; set; }
}

 public class IngredientsViewModel
{
    [Required]
    public string Name { get; set; }
    [Required]
    public int Quantity { get; set; }
    [Required]
    public Int64 Dish_ID { get; set; }
}

我正在使用Automapper在它们之间进行映射。以下是我用于将菜单映射到DishViewModel的代码

public DishViewModel Create(Dish dish)
    {
        Mapper.Initialize(cfg => cfg.CreateMap<Dish, DishViewModel>()
        .ForMember(s => s.Ingredients, c => c.MapFrom(m => m.Ingredients))
        );
        DishViewModel dishViewModel = Mapper.Map<DishViewModel>(dish);
        return dishViewModel;
    }

我在上述过程中遇到以下错误Error in Mapping

任何人都可以指导我在上述过程中做错了什么。

由于

1 个答案:

答案 0 :(得分:5)

您必须为Random.nextInt()创建映射配置,类似于IngredientsDish的映射

正如您在“异常”中所看到的那样,缺少地图配置。

将配置添加到DishViewModel

Mapper.Initialize

更改为:

Mapper.Initialize(

    // Here you are only adding one config.

cfg => cfg.CreateMap<Dish, DishViewModel>()
        .ForMember(s => s.Ingredients, c => c.MapFrom(m => m.Ingredients))

        );

此外,您不需要以下内容:

Mapper.Initialize(cfg =>
    {
          cfg.CreateMap<Dish, DishViewModel>()
                .ForMember(s => s.Ingredients, c => c.MapFrom(m => m.Ingredients));

           cfg.CreateMap<Ingredients, IngredientsViewModel>();

     });

由于属性的名称相同,AutoMapper将自动映射属性。

所以你可以使用它:

.ForMember(s => s.Ingredients, c => c.MapFrom(m => m.Ingredients));