【问题标题】:AutoMapper with different instances具有不同实例的 AutoMapper
【发布时间】:2015-06-09 12:56:15
【问题描述】:

我有两门课

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

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

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

在这里,在函数中,我正在获取状态为 Active 和 Inactive 的患者列表。

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

  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 两者。 我怎样才能做到这一点?

【问题讨论】:

标签: c#-4.0 entity-framework-6 automapper


【解决方案1】:

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

    AutoMapper.Mapper.Reset();

它成功了。参考这个链接 http://blog.cymen.org/2011/06/17/automapper-and-mapper-reset/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-10
    • 2014-08-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多