如何使用valueInjecter而不是AutoMapper来进行这些映射

本文关键字:映射 AutoMapper valueInjecter 何使用 | 更新日期: 2023-09-27 18:28:58

我以前在一个项目中使用过Automapper,现在我想为另一个项目使用ValueInjecter。

这些是ViewModels

public class ApplicantListViewModel : BaseViewModel
{
    public int Id {get; set;}
    public string Name {get;set;}
    public string CourseName {get;set;}
}
public class CourseListViewModel : BaseViewModel
{
    public int Id {get; set;}
    public string Name {get;set;}
    public int Applicants {get;set;}
}

这些是我的DTO

public class Course : BaseEntity
{
    public string Name { get; set; }
    public virtual IList<Applicant> Applicants { get; set; }
}
public class Applicant : BaseEntity
{
    public string Name { get; set; }
    public int CourseId { get; set; }
    public virtual Course Course { get; set; }
}

我可以使用Automapper将DTO映射到ViewModels,如下所示

 AutoMapper.Mapper.CreateMap<Applicant, ApplicantListViewModel>();
 AutoMapper.Mapper.CreateMap<Course, CourseListViewModel>()
                .ForMember(s => s.Applicants, d => d.MapFrom(s => s.Applicants.Count));

然后自动将课程映射到CourseListViewModel,并将申请人映射到ApplicantListViewModel。当它映射时,我可以看到ApplicantListViewModel的CourseName属性从Course.Name中获取值,而无需使用AutoMapper进行任何特殊配置,但ValueInjector不会映射(CourseName变为null)。此外,CourseListView Model的Apparters属性也从Appartners.Count中获取值。

如何通过ValueInjecter简化这些映射?

如何使用valueInjecter而不是AutoMapper来进行这些映射

看一看平坦、不平坦的

以下是您的代码示例:

    [Test]
    public void Mapper()
    {
        var course = new Course { Name = "just a simple name" };
        var applicantList = new List<Applicant>()
            {
                new Applicant {Course = course, CourseId = 1, Name = "Applicant Course 1"}, 
                new Applicant {Course = course, CourseId = 2, Name = "Applicant Course 2"}
            };
        course.Applicants = applicantList;
        var courseView = new CourseListViewModel();
        courseView.InjectFrom<FlatLoopValueInjection>(course);
        //just set other props here, like you did with AutoMapper.
        courseView.Applicants = course.Applicants.Count;
        var applicantViewList = applicantList.Select(s =>
            {
                var applicantView = new ApplicantListViewModel();
                applicantView.InjectFrom<FlatLoopValueInjection>(s);
                return applicantView;
            }).ToList();
        Assert.AreEqual(course.Name, courseView.Name);
        Assert.AreEqual(course.Applicants.Count, courseView.Applicants);
        Assert.AreEqual(applicantList[0].Name, applicantViewList[0].Name);
        Assert.AreEqual(applicantList[0].Course.Name, applicantViewList[0].CourseName);
    }

希望有帮助!