AutoMapper with different instances

133 Views Asked by At

I have two classes

public class PatientViewModel
{
    public int Id { get; set; }    

    public string FirstName { get; set; }

    public string MiddleName { get; set; }

    public string LastName { get; set; }        

    public DateTime DOB { get; set; }

}

and

public class PatientExtended : PatientViewModel
{

    public string FullName { get; set; }

    public string IsActive { get; set; }

    public class IsActiveResolver : ValueResolver<bool, string>
    {
        protected override string ResolveCore(bool source)
        {
            return source ? "Active" : "InActive";
        }
    }
}

I mapped entityframework Patient object with my custom class PatientViewModel successfully in the following function. Its giving the expected result.

  private List<PatientExtended> GetPatientFromDB()
  {
        IList<Patient> patient = db.Patients.ToList();

        Mapper.CreateMap<Patient, PatientExtended>().ForMember(s =>s.IsActive,m => m.ResolveUsing<MvcWithAutoMapper.Models.PatientExtended.IsActiveResolver>().FromMember(x => x.IsActive));            

        IList<PatientExtended> patientViewItem =  Mapper.Map<IList<Patient>,IList<PatientExtended>>(patient);  

        return patientViewItem.ToList();
 }

Here, in the function I am getting list of patients with the status Active and Inactive.

Now, I am trying to get the details of a patient in the function

  public ActionResult Details(int id)
  {
        Patient patient = db.Patients.Where(x => x.Id == id).FirstOrDefault();            

        Mapper.CreateMap<Patient, PatientExtended>().ForMember(dest => dest.IsActive, opt => opt.MapFrom(src => src.IsActive == true ? "Active" : "InActive")).ForMember(cv => cv.FullName, m => m.MapFrom(s => s.FirstName + " " + s.MiddleName + " " + s.LastName));

        patientViewItem = Mapper.Map<Patient, PatientExtended>(patient);

        return View(patientViewItem);
    }

Here, I am trying to get the FullName of the patient. But, its coming null. Then I added .ForMember(cv => cv.FullName, m => m.MapFrom(s => s.FirstName + " " + s.MiddleName + " " + s.LastName)); in GetPatientFromDB() function CreateMap method and was able to get FullName in the second function.

Seems, AutoMapper work like static. Then in my scenario how can I create the different instances of CreateMap in different functions? Because, at one place I want to have only Status and other place I want to have Status and FullName both. How can I achieve this?

1

There are 1 best solutions below

0
On BEST ANSWER

Thank you for reply friends. I found the solution. Before and after using AutoMapper, I reset the AutoMapper

    AutoMapper.Mapper.Reset();

and it worked.Refer this link http://blog.cymen.org/2011/06/17/automapper-and-mapper-reset/