EF 核心和自动映射器。映射关系一对多

EF Core and Automapper. Mapping relationship one-to-many

我目前正在一个项目中使用 AutoMapper 运行 代码优先 Entity Framework。

这里只是简单的实体和 DTO:

// DTO Profile
public class CreateOrEditProfileDto 
{        
    public string Code { get; set; }
    public string Name { get; set; }

    public List<RouteDto> Routes { get; set; }
}

// entity Profile
public class Profile
{       
    public virtual string Code { get; set; }
    public virtual string Name { get; set; }
}

// DTO Route
public class RouteDto 
{
    public string DriverName { get; set; }
    public string DriverSurname { get; set; }
    public string Phone { get; set; }
    public string Email { get; set; }
    public int ProfileId { get; set; }
}

//entity Route
public class Route
{
    public virtual string DriverName { get; set; }
    public virtual string DriverSurname { get; set; }
    public virtual string Phone { get; set; }
    public virtual string Email { get; set; }
    public virtual int ProfileId { get; set; }

    [ForeignKey("ProfileId")]
    public Profile ProfileFk { get; set; }
}

//Mapper
configuration.CreateMap<RouteDto, Route>().ReverseMap();
// configuration.CreateMap<CreateOrEditProfileDto, Profile>().ReverseMap();

// this type of configuration give the error written below
configuration.CreateMap<CreateOrEditProfileDto, Profile>()
     .ForMember(dest => dest, opt =>
        opt.MapFrom(src => src.Routes.Select(x =>
           new Route()
              {
                  ProfileId = x.ProfileId,
                  DriverName = x.DriverName,
                  DriverSurname = x.DriverSurname,
                  Phone = x.Phone,
                  Email = x.Email,
              }
           )
        )
     );

我有点困惑,我正在尝试映射 Profile 和 Route 之间的一对多关系,Route 有 Profile 的外键。单个配置文件可以有更多路由。所以,我想创建一个配置文件并附加路由列表,但是当我编译解决方案时,我得到这个错误:

AutoMapper.AutoMapperConfigurationException: 'Custom configuration for members is only supported for top-level individual members on a type.'

有谁知道解决这个映射的最佳方法吗?

此致

因为List<RouteDto>映射到Profile,类型不匹配。您需要在 Profile.

中添加一个 属性
 public class Profile
{
    public virtual string Code { get; set; }
    public virtual string Name { get; set; }
    public List<Route> Routes { get; set; }
}

需要指定映射属性dest.Routes。然后,Routes 将被自动映射。

  CreateMap<CreateOrEditProfileDto, EntityProfile>()
          .ForMember(dest => dest.Routes, opt =>
             opt.MapFrom(src => src.Routes.Select(x=>
             new Route()
             {
                 ProfileId = x.ProfileId,
                 DriverName = x.DriverName,
                 DriverSurname = x.DriverSurname,
                 Phone = x.Phone,
                 Email = x.Email,
             }
             ))
          );