如何配置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);
}
AutoMapper配置
Mapper.CreateMap<Document, DocumentEditModel>();
Mapper.CreateMap<DocumentEditModel, Document>();
答案 0 :(得分:1)
由于关联是多对多的,因此您只需在数据库中创建联结记录。一种方便的方法是清除收集和添加项目。我们以Document.PatientTypes
为例:
var document = Mapper.Map(model, _documentRepository.Find(model.ID));
document.DateModified = DateTime.Now;
// Set the new associatins with PatientTypes
document.PatientTypes.Clear();
foreach(var pt in model.PatientTypeList.Select(id => new PatientType{Id = id}))
{
document.PatientTypes.Add(pt);
}
_documentRepository.InsertOrUpdate(document);
_documentRepository.Save();
(我不得不假设属性名称)
这里发生的是DocumentPatientTypes
联结表中的现有记录被一组新记录替换。这是通过使用所谓的stub entities new PatientType
来完成的。您不必首先从数据库中获取真实的,因为EF需要的唯一内容是创建新联结记录的Id值。
如你所见,我默默地将Automapper排除在外。将整数列表映射到PatientType
会有点过分。 Select
很容易,有一点经验就会立即识别出存根实体模式,否则会被Mapper.Map
语句隐藏。