Boy Pasmo
Boy Pasmo

Reputation: 8511

how to map one-to-many relationship with custom mapping

I'm learning on how to use AutoMapper and I'm getting the hang of it. But what if you have a one-to-many relationship? You can do something like this, right?

But then, what if the scenario was something like this wherein you only want the last value in the list. Let me demonstrate it.

public class Item
{
  public Item()
  {
    Prices = new HashSet<Price>();
  }
  public int Id { get; set; }
  public string Name { get; set; }

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

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

  public virtual Item Item { get; set; }
}

public class ItemVM
{
  public string Name { get; set; }
  public decimal Price { get; set; }
}

Now, the catch is I want to map the ItemVM.Price = The last value in Price class. Is this possible?

I have tried something like this, but didn't worked.

Mapper.CreateMap<Item, ItemVM>()
  .ForMember(dto => dto.Price, opt => opt.MapFrom(s => s.Prices.LastOrDefault().Price));

then

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

But gives me an error of InvalidOperation. Any help would be much appreciated. Thanks!

Upvotes: 1

Views: 981

Answers (1)

Joanvo
Joanvo

Reputation: 5827

Your mapping looks good, but maybe you are getting a NullReferenceException. I would map it that way:

[Edited]

Mapper.CreateMap<Item, ItemVM>()
.ForMember(dto => dto.Price, opt => 
           opt.MapFrom(s => s.Prices.Any()?
           s.Prices.OrderByDescending ().First ().Price:0));

Upvotes: 4

Related Questions