使用Automapper将类内部列表映射到另一个类中的列表

时间:2016-03-14 09:34:34

标签: c#

我正在尝试使用Project_Master类中的属性Project_Locations在类Project中映射属性ProjectLocation

public class Project
{
   public int ProjectId { get; set; }
   public string ProjectCode { get; set; }
   public virtual ICollection<ProjectLocation> ProjectLocation { get; set; }
}

public partial class Project_Master
{
  public int ProjectId { get; set; }
  public string ProjectCode { get; set; }
  public virtual ICollection<Project_Locations> Project_Locations { get; set; }
}

public partial class Project_Locations
{
    public int ProjectLocationId { get; set; }
    public int ProjectId { get; set; }
    public virtual Project_Master Project_Master { get; set; }
}

public class ProjectLocation
{
    public int ProjectLocationId { get; set; }
    public int ProjectId { get; set; }
    public virtual Project Project { get; set; }
}

我的映射器配置

CreateMap<Models.Project.Project, Dal.Repository.Project_Master>();
CreateMap<Models.Project.ProjectLocation, Dal.Repository.Project_Locations>();

班级实例

Models.Project.Project project = new Models.Project.Project();
project.ProjectId = 1;
project.ProjectLocation = new List<Models.Project.ProjectLocation>();
project.ProjectLocation.Add(new Models.Project.ProjectLocation() { LocationId = 2, ProjectId = 1 });

映射代码

var proj = mapper.Map<Dal.Repository.Project_Master>(project);

1 个答案:

答案 0 :(得分:1)

我在配置文件中添加了以下内容

CreateMap<Models.Project.Project, Dal.Repository.Project_Master>().ForMember(dest => dest.Project_Locations, opt => opt.MapFrom(src=> src.ProjectLocation));