2014-11-02 87 views
0

我之前在其中一個項目中使用了Automapper,現在我想爲另一個項目使用ValueInjecter。如何通過使用valueInjecter而不是AutoMapper來實現這些映射

這些的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; } 

} 

我可以像下面DTO的映射到的ViewModels某物Automapper

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)。另外CourseListViewModel的申請人屬性從Applicants.Count中獲得它的價值,幾乎沒有配置。

如何通過ValueInjecter更輕鬆地完成這些映射?

回答

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

希望它能幫助!