从单个DTO到多个一对一实体的Automapper 8

时间:2019-03-19 09:27:35

标签: c# entity-framework-6 asp.net-web-api2 automapper dto

我将Automapper 8与Entity Framework 6.2一起使用,但不了解如何将DTO拆分为多个实体。

DTO模型为:

public class DTOMachine {
    public int MachineNumber { get; set; }
    public string ComputerName { get; set; }
    public string Cpu { get; set; }
}

实体模型是:

public class Machine
{
    [Key]
    public int Id { get; set; }

    public string ComputerName { get; set; }

    public virtual MachineHW MachineHW { get; set; }
}

与MachineHW具有一对一关系:

public class MachineHW
{

    [ForeignKey("Machine"), Key]
    public int MachineId { get; set; }

    public string CpuName { get; set; }

    public virtual Machine Machine { get; set; }

}

具有映射关系的API是:

[HttpPost]
public IHttpActionResult SetMachineData(List<DTOWorkload> Json)
{

    var config = new MapperConfiguration(
        cfg =>
        {
            cfg.CreateMap<DTOMachine, Machine>()
               .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.MachineNumber))
               .ForPath(d => d.MachineHW.MachineId, o => o.MapFrom(s => s.MachineNumber));
            cfg.CreateMap<DTOMachine, WorkloadMachineHW>()
               .ForPath(d => d.WorkloadMachineId, o => o.MapFrom(s => s.MachineNumber))
               .ForMember(dest => dest.CpuName, opt => opt.MapFrom(src => src.Cpu))                    
            });

    IMapper mapper = config.CreateMapper();
    var test_map = mapper.Map<List<DTOWorkload>, List<Machine>>(Json);

    return Ok();
}

test_map包含具有正确MachineId的MachineHW对象,但所有其他属性仍然为空。我的地图出了什么问题?


如果我使用手动映射,则可以使用,但是我认为在手动模式下使用自动工具没用!

cfg.CreateMap<DTOWorkloadMachineInfo, WorkloadMachine>()
   .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.MachineNumber))
   .ForPath(dest => dest.MachineHW.CpuName, o => o.MapFrom(src => src.Cpu));

0 个答案:

没有答案