1

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!

Community
  • 1
  • 1
Boy Pasmo
  • 8,021
  • 13
  • 42
  • 67

1 Answers1

4

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));
Joanvo
  • 5,677
  • 2
  • 25
  • 35
  • What does `?s` and `:0` do for? I'm new in `Linq` by the way. Think you could enlighten me more? It would be a great help. – Boy Pasmo Jun 27 '14 at 16:28
  • `a?x:y` means `if (a) x; else b;`. In this case it assings zero if the collection does not have any item. That prevents the exception. – Joanvo Jun 27 '14 at 16:32
  • Ohhh! A `ternary operator` Didn't realize that. I thought it was on linq itself. But I tried yours but gives me an `System.NotSupportedException`. Really stuck here. Been banging my head since last night. – Boy Pasmo Jun 27 '14 at 16:37
  • In that case you might be getting something like this:http://stackoverflow.com/questions/7253529/last-and-lastordefault-not-supported . Then try to change `LastOrDefault` and use `Reverse().First ()`, `OrderByDescending ().First ()` or something like this? – Joanvo Jun 27 '14 at 16:43
  • WOW! It actually works! Thank you so much mate. Now I can move on. Really. Thank you so much. Think you can add that in the answer above? For other's reference :) – Boy Pasmo Jun 27 '14 at 16:55