使用AutoMapper将ListBoxT项映射到ICollection

时间:2013-04-08 17:37:29

标签: c# entity-framework automapper

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

1 个答案:

答案 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语句隐藏。