【发布时间】: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 而在另一个地方我想拥有 具有 Status 和 FullName 两者。 我怎样才能做到这一点?
【问题讨论】:
-
我遵循相同的模式,但我为每种类型的视图创建了一个特定的视图模型。 Mapper.CreateMap
。我个人认为没有办法按照你的想法去做。
标签: c#-4.0 entity-framework-6 automapper