使用 Automapper 更改 Collection

Using Automapper to change Collection

我在 C# 中有两个具有一对多关系的模型:

public class Make
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<Model> Models { get; set; }
}

public class Model
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Make Make { get; set; }
    public int MakeId { get; set; }
}

DTO 如下:

public class MakeDto
{
    public int Id { get; set; }
    public int ModelId { get; set; }
    public ICollection<Models> Models { get; set; }
}

我在更新操作中使用 Automapper 映射 DTO,问题是 add/remove 集合工作正常但 添加新项目更新现有项目 无效。

public AutoMapperProfile()
{

    CreateMap<MakeDto, Make>()
        .ForMember(m => m.Id, opt => opt.Ignore())
        .ForMember(m => m.Model, opt => opt.Ignore())
        .AfterMap((dt, m) =>
        {

            // Remove Model
            var removedModel = m.Model.Where(x => !dt.Model.Any(f => f.Id == x.Id)).ToList();
            foreach (var m in removedModel)
                m.Model.Remove(m);

            // Add new Model
            var addedModel = dt.Model.Where(x => !m.Model.
            Any(f => f.Id == x.Id))
            .Select(x => new Model
            {
                Id = dt.Id,
                Name = x.Name
            })
            .ToList();            
            foreach (var m in addedModel)
                m.Model.Add(m);


        }).AfterMap((dt, m) =>
        {
            //Update Model
            m.Model = m.Model.Where(x => dt.Model.Any(f => f.Id == x.Id))
            .Select(x => new Model
            {
                Name = dt.Model.FirstOrDefault(x => x.Id == x.Id).Name,
            }).ToList();
        });
}

为了回答我的问题和未来的读者,我使用 Automapper.Collection 如下:

        var mapper = new MapperConfiguration(
            cfg =>
            {
                cfg.AddCollectionMappers();
                cfg.CreateMap<MakeDto, Make>()
                    .EqualityComparison((src, dst) => src.Id == dst.Id);
                cfg.CreateMap<Model, Model>()
                    .ForMember(x => x.Make, opt => opt.Ignore())
                    .EqualityComparison((src, dst) => src.Id == dst.Id);
            })
            .CreateMapper();
        mapper.Map<MakeDto, Make>(makeDto, make);
        await _unitOfWork.CompleteAsync();

另外,如果有兴趣,请参阅此 link