用AutoMapper将ListBoxFor项映射到iccollection

本文关键字:映射 iccollection ListBoxFor AutoMapper | 更新日期: 2023-09-27 18:08:00

我如何配置AutoMapper映射一个整数数组(从一个多选择MVC ListBoxFor元素填充)到我的域对象的iccollection属性?基本上,我想将域对象的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>();

用AutoMapper将ListBoxFor项映射到iccollection

由于关联是多对多的,您只需在数据库中创建连接记录。一种方便的方法是清除集合并向其中添加项。以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连接表中的现有记录被一组新记录替换。这是通过使用所谓的存根实体,即new PatientType来完成的。您不必首先从数据库中获取真实的数据,因为EF只需要Id值来创建新的连接记录。

如你所见,我默默地把Automapper从等式中去掉了。将一个整数列表映射到PatientType将是过度的。Select很简单,只要有一点经验,就可以立即识别出存根实体模式,否则它将被Mapper.Map语句隐藏。