[英]automapper create.map() to a collection property
How do you map to a collection of property but only interested with the last record of the collection. 您如何映射到属性集合,但仅对集合的最后一条记录感兴趣。
Say, something like. 说,像。
public class ItemDTO <-- destination class
{
public string Name { get; set; }
public decimal PricesPrice { get; set; }
}
public class Item <-- Source class
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Price> Prices { get; set; }
}
public class Price <-- Source class
{
public int Id { get; set; }
public int ItemId { get; set; }
public decimal Price { get; set; }
public virtual Item Item { get; set; }
}
Then I have tried something like this, but doesn't seems to be right. 然后我尝试了类似的方法,但似乎不正确。
Mapper.CreateMap<Item, ItemDTO>()
.ForMember(dto => dto.PricesPrice, opt => opt.MapFrom(s => s.Prices.LastOrDefault().Price));
EDIT: And then after that I did a Projection because If I use Mapper.Map()
It will return the entire result set which is not what I want, I only want the values I needed. 编辑:然后在那之后我做了一个投影,因为如果我使用Mapper.Map()
它将返回不是我想要的整个结果集,我只想要我需要的值。 So I did something like this: 所以我做了这样的事情:
Project().To<ItemDTO>()
Well, basically, I want something like this: 好吧,基本上,我想要这样的东西:
from item in SomeDbContext.Items
where item.ItemId == 1
select new ItemDTO
{
Name = item.Name,
PricesPrice = item.Prices.LastOrDefault()
}
Can above code be done using AutoMapper
? 上面的代码可以使用AutoMapper
完成吗?
I think I understand what you are trying to do now. 我想我知道您现在要做什么。
Try this 尝试这个
from item in SomeDbContext.Items
where item.ItemId == 1
select Mapper.Map<ItemDTO>(item)
or you could use LINQ 或者你可以使用LINQ
SomeDbContext.Items.Where(i=> i.ItemId == 1).Select(Mapper.Map<ItemDTO>)
Both of these will return you a list of ItemDTO object where the ItemId is 1 这两个都将返回ItemDTO对象的列表,其中ItemId为1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.