So my DB has a one-to-many association between a customer and orders.
Mapping the data to show a customer and his orders is no problem. But is there a way to map these when creating a customer?
For example:
“The very basic viewModel just to test the Mapping”
public class CVM
{
public string ContactName { get; set; } //Part of the Customer Table
public DateTime OrderDate { get; set; } //Part of the Orders Table and
//would have to be passed into the Orders List of the EF-Customer-Object
}
So the create view just has 2 inputs for Name and Date.
“The very basic controller just to test the Mapping ;)”
[HttpPost]
public ActionResult Create(CVM model)
{
Mapper.CreateMap<CVM, Customer>();
Customer customer = Mapper.Map<CVM, Customer>(model);
return View();
}
So ContactName gets mapped properly. The Problem is the OrderDate. AutoMapper would have to create an Order instance, set the value of OrderDate and pass it to the OrdersCollection of the Customer object. Is AutoMapper able to do this or am I totally wrong?
Hope you understand my explanation and someone has an Answer to me.
Thanks Folks
I think you are going about it the wrong way. What you should be doing is to instantiate a
Customerinstance and then map it s properties using AutoMapper.Thus, your code would look like:
BTW, you should make sure to have
Mapper.CreateMap<CVM, Customer>()directives only during application startup, otherwise you are needlessly performing this (possibly costly) step on every request.Edit
It seems I read the original question wrong. If the aim is to create a Customer with associated objects, then Automapper can help you in a few different ways (I am going forward with the Person/PhoneNumber example you gave in the comments).
Given that your Entities and View Models are:
then you have a few alternatives:
PhoneNumberVMinstance is mapped to aPhoneNumberinstance, orMapper.CreateMap<PhoneNumberVM, PhoneNumber>()and just callMapper.Map<PersonVM, Person>(model)to have your model mapped to your entity.Of course, you would have to make sure that your model gets constructed properly, but that is not very hard as long as you use the same model to generate your HTML form.