1

如何配置 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>();
4

1 回答 1

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联结表中的现有记录被一组新记录替换。这是通过使用所谓的存根实体s 来完成的new PatientType。您不必先从数据库中获取真实数据,因为 EF 唯一需要的是 Id 值来创建新的联结记录。

如您所见,我默默地将 Automapper 排除在外。将整数列表映射到PatientType. 这Select很容易,只要有一点经验,就可以立即识别出存根实体模式,否则它会被Mapper.Map语句隐藏。

于 2013-04-08T18:54:22.427 回答