【发布时间】:2014-06-26 16:08:47
【问题描述】:
我正在学习如何使用AutoMapper,并且已经掌握了窍门。但是如果你有一个一对多的关系呢?你可以做this之类的事情,对吧?
但是,如果场景是这样的,您只需要列表中的最后一个值。让我演示一下。
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; }
}
现在,问题是我想映射ItemVM.Price = The last value in Price class。这可能吗?
我尝试过类似的方法,但没有成功。
Mapper.CreateMap<Item, ItemVM>()
.ForMember(dto => dto.Price, opt => opt.MapFrom(s => s.Prices.LastOrDefault().Price));
然后
var items = All.Project().To<ItemVM>();
但是给了我一个 InvalidOperation 的错误。任何帮助将非常感激。谢谢!
【问题讨论】:
-
你如何定义
the last value?按日期,还是按 ID? -
我想通过
Price.ItemId获取Item.Prices列表中的最后一个值
标签: c# automapper