如何配置 AutoMapper 以将整数数组(从多选 MVC ListBoxFor 元素填充)映射到我的域对象的 ICollection 属性?基本上我想将域对象的 PatientTypes 和 ProviderTypes 属性设置为用户在列表框中选择的任何内容,然后将对象保存回数据库。
域对象
public class Document
{
public int ID { get; set; }
public virtual ICollection<PatientType> PatientTypes { get; set; }
public virtual ICollection<ProviderType> ProviderTypes { get; set; }
}
查看模型
public class DocumentEditModel
{
public int ID { get; set; }
[DisplayName("Patient Type")]
public int[] SelectedPatientTypes { get; set; }
public SelectList PatientTypeList { get; set; }
[DisplayName("Provider Type")]
public int[] SelectedProviderTypes { get; set; }
public SelectList ProviderTypeList { get; set; }
}
控制器
public virtual ActionResult Edit(int pid)
{
var model = Mapper.Map<DocumentEditModel>(_documentRepository.Find(pid));
model.ProviderTypeList = new SelectList(_providerTypeRepository.All.OrderBy(x => x.Value), "ID", "Value");
model.PatientTypeList = new SelectList(_patientTypeRepository.All.OrderBy(x => x.Value), "ID", "Value");
return View(model);
}
[HttpPost]
public virtual ActionResult Edit(DocumentEditModel model)
{
if (ModelState.IsValid)
{
var document = Mapper.Map(model, _documentRepository.Find(model.ID));
document.DateModified = DateTime.Now;
_documentRepository.InsertOrUpdate(document);
_documentRepository.Save();
return null;
}
model.ProviderTypeList = new SelectList(_providerTypeRepository.All.OrderBy(x => x.Value), "ID", "Value");
model.PatientTypeList = new SelectList(_patientTypeRepository.All.OrderBy(x => x.Value), "ID", "Value");
return View(model);
}
自动映射器配置
Mapper.CreateMap<Document, DocumentEditModel>();
Mapper.CreateMap<DocumentEditModel, Document>();