带有AutoMapper的EF Core

时间:2020-08-06 21:53:56

标签: automapper asp.net-core-webapi dto ef-core-2.1

我有一个包含属性和模型的DTO,例如,一个学生可以有多个模块,而一个模块可以与一个以上学生相关联。属性可以很好地映射,但是模型不能映射。

 public class GetStudentByIdMapping : Profile
{
    public GetStudentByIdMapping()
    {
        CreateMap<Student,StudentDetails>();
        CreateMap<Module, StudentDetails>()
            .ForPath(dest => dest.StudentModules.ModuleName, opt => opt.MapFrom(m => m.ModuleName))
            .ForPath(dest => dest.StudentModules.ModuleCode, opt => opt.MapFrom(m => m.ModuleCode))
            .ForPath(dest => dest.StudentModules.Description, opt => opt.MapFrom(m => m.Description))
            .ReverseMap();


    }
}


    public async Task<StudentDetails> GetStudent(int studentId)
    {
        var student = context.Student
                             .Where(s => s.StudentId == studentId)
                             .FirstOrDefault();

        var module = await context.Order
                           .Include(m => m.Module)
                           .Where(o => o.StudentId == studentId)
                           .Select(m => m.Module).ToListAsync();


        var studMap =  Mapper.Map<StudentDetails>(student);
        Mapper.Map<StudentDetails>(module);


        return studMap;
    }

这些是我想映射到StudentDetails ViewModel中的模型模型的ViewModels

public class StudentDetails
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string PhoneNumber { get; set; }

    public StudentModule StudentModules { get; set; }

}
public class StudentModule
{
    public string ModuleName { get; set; }
    public string ModuleCode { get; set; }
    public string Description { get; set; }

}

这些是我由EF Core生成的实体

public partial class Student
{
    public Student()
    {
        Order = new HashSet<Order>();
    }

    public int StudentId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string PhoneNumber { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }

    public virtual ICollection<Order> Order { get; set; }
}

public partial class Module
{
    public Module()
    {
        Order = new HashSet<Order>();
    }

    public int ModuleId { get; set; }
    public int? LectureId { get; set; }
    public string ModuleName { get; set; }
    public string ModuleCode { get; set; }
    public string Description { get; set; }
    public string ModulePath { get; set; }

    public virtual Lecture Lecture { get; set; }
    public virtual ICollection<Order> Order { get; set; }
}

1 个答案:

答案 0 :(得分:0)

您只需将创建的目的地传递给第二个地图通话

映射时只需尝试以下代码:

 var studMap = Mapper.Map<Student,StudentDetails>(student);
 Mapper.Map<Module,StudentDetails>(module,studMap);

然后studMap将收到所有映射字段的值。

相关问题