具有不同实例的 AutoMapper

AutoMapper with different instances

我有两个 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; }

}

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

我在以下函数中成功地将 entityframework Patient 对象映射到我的自定义 class PatientViewModel 对象。它给出了预期的结果。

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

在这里,我在函数中获取状态为活动和非活动的患者列表。

现在,我正在尝试在函数中获取患者的详细信息

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

在这里,我试图获取患者的 FullName。但是,它即将无效。然后我添加了 .ForMember(cv => cv.FullName, m => m.MapFrom(s => s.FirstName + " " + s.MiddleName + " " + s.LastName));GetPatientFromDB() 函数中 CreateMap 方法,并且能够在第二个函数中获取 FullName。

似乎,AutoMapper 像静态一样工作。那么在我的场景中,我该如何创建 CreateMap 在不同函数中的不同实例? 因为,在一个地方我只想拥有 Status 而在其他地方我想要 有 StatusFullName 两者。 我怎样才能做到这一点?

谢谢回复的朋友。我找到了解决方案。使用AutoMapper前后,我重置了AutoMapper

    AutoMapper.Mapper.Reset();

它 worked.Refer 这个 link http://blog.cymen.org/2011/06/17/automapper-and-mapper-reset/