0

I have used Automapper in one of my project before, now I want to use ValueInjecter for the other one.

These are 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;}
}

These are my DTOs

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

}

I can map DTOs to ViewModels sth like below with Automapper

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

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

Then it is automatically map Course to CourseListViewModel and Applicant to ApplicantListViewModel. When it maps I can see that ApplicantListViewModel's CourseName' property gets its value from Course.Name without any special configuration by using AutoMapper but ValueInjector doesnt map(CourseName become null) it. Also CourseListViewModel's Applicants property gets its value from Applicants.Count with little configuration.

How to do these mappings by ValueInjecter easier ?

Barış Velioğlu
  • 5,709
  • 15
  • 59
  • 105

1 Answers1

1

Take a look at flattening, unflattening

Here a example of your code:

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

Hope it Helps!

WilsonM
  • 11
  • 1