Boy Pasmo
Boy Pasmo

Reputation: 8481

how to do mapping in automapper for classes with complex relationship

public class Item
{
  public string Name { get; set; }

  public virtual ICollection<Stock> Stocks { get; set; }
  public virtual ICollection<Price> Prices { get; set; }

  -- remove some code for brevity --
}

public Stock
{
  public int Id { get; set; }
  public int ItemId { get; set; }
  public int StorageId { get; set; }
  public float Amount { get; set; }

  public virtual Item Item { get; set; }
  public virtual Storage Storage { get; set; }

  -- remove some code for brevity --
}

public class Storage
{
  public string Name { get; set; }

  public virtual ICollection<Stock> Stocks { get; set; }

  -- remove some code for brevity --
}

public class SPrice
{
  public decimal Price { get; set; }
  public int decimal ItemId { get; set; }

  public virtual Item Item { get; set; }

  -- remove some code for brevity --
}

Above is my POCO classes And I'm just starting out using Automapper. I have little complex relationship. I'm confuse on what class is my source class and how to do the mapping.

Because what I want to have is only.

For clarity I want them to be displayed as something like this:

Name   : Snack bar
Price  : $1.00
Stocks :
         Storages    | How many
         Storage1    | 23
         Storage2    | 24
         Storage3    | 10

So far I only have is the ItemName and ItemPricethat goes like this:

Mapper.CreateMap<Item, ItemDTO>()
      .ForMember(dto => dto.Price, opt => 
          opt.MapFrom(s => s.Prices.Any() ? s.Price.OrderByDescending(i => i.Id).FirstOrDefault() : 0m));

Then storing them as like this:

var items = _itemService.All.Project().To<ItemDTO>();

In a nutshell, how to do the mapping for the rest of the property member? Any tips? A demo code would be great. Many thanks!

Upvotes: 0

Views: 1024

Answers (1)

ovm
ovm

Reputation: 2532

Here is an example to add to my comment.

Lets say you have these classes

Model

public class Item
{
  public string Name { get; set; }

  public virtual ICollection<Stock> Stocks { get; set; }
  public virtual ICollection<Price> Prices { get; set; }
}

ViewModel

public class ItemViewModel
{
  public string Name { get; set; }

  public StockViewModel [] Stocks { get; set; }
  public PriceViewModel [] Prices { get; set; }
}

You just would have to configure the Automapper like so:

AutoMapper.CreateMap<Item,ItemViewModel>();
AutoMapper.CreateMap<Stock,StockViewModel>();
AutoMapper.CreateMap<Price,PriceViewModel>();

The AutoMapper would then determine the mappings of the subcomposita lists automatically.

Upvotes: 1

Related Questions