Automapper不映射某些道具

时间:2019-05-30 10:10:39

标签: c# asp.net-web-api automapper dto

我有几个域实体和DTO,并使用Automapper在它们之间传输数据。

代码如下:

public class Ingredient
{
    public int IngredientId { get; set; }

    [Required]
    [Index(IsUnique = true)]
    [StringLength(400)]
    public string Name { get; set; }
    public string Description { get; set; }

    public double? Carbs { get; set; }
    public double? Prots { get; set; }
    public double? Fats { get; set; }
    public double? Cals { get; set; }

    public string Photo { get; set; }

    public virtual ICollection<Dish> Dishes { get; set; } = new List<Dish>();
}

public class IngredientDetailedDTO : IIngredientDTO
{
    public int IngredientId { get; set; }

    [Required]
    [StringLength(400)]
    public string Name { get; set; }

    public string Description { get; set; }

    public double? Carbs { get; set; }
    public double? Prots { get; set; }
    public double? Fats { get; set; }
    public double? Cals { get; set; }

    public string Photo { get; set; }
}

在做某件事之前,我想检查一下我的数据库成分ID是否是ID(来自dto),所以我的自动映射器配置如下:

var config = new MapperConfiguration(
                 x =>
                 {
                      // Other maps
                      x.CreateMap<IngredientDetailedDTO, Ingredient>()
                       .ConstructUsing(o => GetIngr(o));
                 });

_mapper = new Mapper(config);

这是GetIngr函数:

private Ingredient GetIngr(IngredientDetailedDTO dto)
{
    var res = _repos.Ingredients.Find(dto.IngredientId);
    return res ?? new Ingredient()
        {
            Name = dto.Name,
            Description = dto.Description,
            Photo = dto.Photo,
            Prots = dto.Prots,
            Cals = dto.Cals,
            Carbs = dto.Carbs,
            Fats = dto.Fats
        };
}

问题是函数GetIngr返回正确初始化的成分实例(当我调用Map函数时):

https://imgur.com/a/q6l1hkV

但是在接下来的步骤中(当Map函数将值返回到代码时,我得到了类似的东西)

https://ibb.co/xg2k73L

一些道具没有初始化的地方

0 个答案:

没有答案