问题
I have an InvoiceInputModel
with a ProjectId
property which is a reference to a Project
entity. Ideally, I want AutoMapper to be able to map an entire Invoice
entity from an InvoiceInputModel
, which looks like this:
public class InvoiceInputModel
{
public Guid Id { get; set; }
public DateTime Date { get; set; }
public string Reference { get; set; }
public Guid ProjectId { get; set; }
}
Obviously the following is bad:
Mapper.CreateMap<InvoiceInputModel, Invoice>()
.ForMember(src => src.Project, opt => opt.MapFrom(
dest => _unitOfWork.CurrentSession.Get<Project>(dest.ProjectId)
)
);
How do I tell AutoMapper that invoice.Project
should be mapped to a Project
entity based off of the ProjectId
property in InvoiceInputModel
while preserving loose coupling?
Invoice/Edit in my 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);
}
I spotted something about "Resolvers" and ResolveUsing, but I have no experience using it.
How do I tell AutoMapper to do this while preserving loose coupling between my entity models, input models and view models? Or is there a better way?
回答1:
How do I tell AutoMapper that invoice.Project should be mapped to a Project entity based off of the ProjectId property in InvoiceInputModel while preserving loose coupling?
You can't. If AutoMapper is going somewhere else to fetch data, then it's not loose coupled.
You're not modifying the Project
in this particular View anyway - why do you need to set the relationship to Project
, isn't nHibernate smart enough to see that property hasn't changed, and not do anything?
回答2:
I personally have entities in viewmodels instead of IDs, so that binding happens automatically.
http://sprokhorenko.blogspot.com/2011/03/bind-to-entity-id.html
来源:https://stackoverflow.com/questions/5636961/how-should-automapper-access-my-dal