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

时间:2014-11-02 18:06:47

标签: c# .net automapper valueinjecter

我之前在我的一个项目中使用过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映射到ViewModel,如下所示

 AutoMapper.Mapper.CreateMap<Applicant, ApplicantListViewModel>();

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

然后它会自动将Course映射到CourseListViewModel,将Applicant映射到ApplicantListViewModel。当它映射时,我可以看到ApplicantListViewModel的CourseName'属性通过使用AutoMapper而没有任何特殊配置从Course.Name获取其值,但是ValueInjector没有映射(CourseName变为null)它。此外,CourseListViewModel的Applicants属性从Applicants.Count获取其值很少配置。

如何通过ValueInjecter更容易地进行这些映射?

1 个答案:

答案 0 :(得分:1)

查看flatteningunflattening

以下是您的代码示例:

    [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);
    }

希望它有帮助!