【发布时间】:2011-04-12 14:34:40
【问题描述】:
我有一个带有ProjectId 属性的InvoiceInputModel,它是对Project 实体的引用。理想情况下,我希望 AutoMapper 能够从 InvoiceInputModel 映射整个 Invoice 实体,如下所示:
public class InvoiceInputModel
{
public Guid Id { get; set; }
public DateTime Date { get; set; }
public string Reference { get; set; }
public Guid ProjectId { get; set; }
}
显然以下是不好的:
Mapper.CreateMap<InvoiceInputModel, Invoice>()
.ForMember(src => src.Project, opt => opt.MapFrom(
dest => _unitOfWork.CurrentSession.Get<Project>(dest.ProjectId)
)
);
我如何告诉 AutoMapper invoice.Project 应该根据 InvoiceInputModel 中的 ProjectId 属性映射到 Project 实体,同时保持松散耦合?
发票/编辑在我的InvoiceController:
[HttpPost]
[Authorize]
public ActionResult Edit(InvoiceInputModel invoiceInputModel)
{
var invoice = _unitOfWork.CurrentSession.Get<Invoice>(invoiceInputModel.Id);
Mapper.Map<InvoiceInputModel, Invoice>(invoiceInputModel, invoice);
invoice.Project = _unitOfWork.CurrentSession.Get<Project>(invoiceInputModel.ProjectId);
// I want AutoMapper to do the above.
_unitOfWork.CurrentSession.SaveOrUpdate(invoice);
_unitOfWork.Commit();
return View(invoice);
}
我发现了一些关于“解析器”和 ResolveUsing 的内容,但我没有使用它的经验。
如何告诉 AutoMapper 执行此操作,同时保持实体模型、输入模型和视图模型之间的松散耦合?还是有更好的办法?
【问题讨论】:
标签: asp.net-mvc fluent-nhibernate automapper loose-coupling