I have this situation:
// Core Business classes
public class Invoice
{
public Guid Id { get; protected set; }
public int Number { get; set; }
public IList<InvoiceItem> Items { get; protected set; }
}
public class InvoiceItem
{
public Guid Id { get; protected set; }
public string Product { get; set; }
public int Quantity { get; set; }
public decimal Price { get; set; }
}
// MVC Models
public class InvoiceModel
{
public Guid Id { get; set; }
public int Number { get; set; }
public IList<InvoiceItemModel> Items { get; set; }
}
public class InvoiceItemModel
{
public Guid Id { get; set; }
public string Product { get; set; }
public int Quantity { get; set; }
public decimal Price { get; set; }
}
The automapper configuration
public class MyProfile : Profile
{
protected override void Configure()
{
Mapper.CreateMap<Invoice, InvoiceModel>();
Mapper.CreateMap<InvoiceItem, InvoiceItemModel>();
}
}
Then when I want to pass a model to my view, for example to edit an Invoice object, I do:
...
var invoice = Repository.Get<Invoice>(id);
return View("Update", Mapper.Map<InvoiceModel>(invoice));
...
And then I can iterate the Items collection with InvoiceItemModel
s.
The issue is when I want to retrieve a bunch of Invoices, for example in an index.
...
var invoices = Repository.ListAll<Invoice>();
return View("Index", invoices.Select(Mapper.Map<InvoiceModel>).ToList());
...
I don't want the "Items" to be loaded. A better configuration for this case will be:
public class MyFlatProfile : Profile
{
protected override void Configure()
{
Mapper.CreateMap<Invoice, InvoiceModel>()
.ForMember(m => m.Items, opt => opt.Ignore());
Mapper.CreateMap<InvoiceItem, InvoiceItemModel>();
}
}
But I have no idea how to switch between "Profiles". Is there a way to "pick" a particular configuration of mapping?