[英]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
. 上面是我的POCO类,而我刚开始使用
Automapper
。 I have little complex relationship. 我没有什么复杂的关系。 I'm confuse on what class is my
source
class and how to do the mapping. 我对我的
source
类是什么类以及如何进行映射感到困惑。
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 ItemPrice
that goes like this: 到目前为止,我只能是
ItemName
和ItemPrice
认为是这样的:
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!
非常感谢!
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:
AutoMapper.CreateMap<Item,ItemViewModel>();
AutoMapper.CreateMap<Stock,StockViewModel>();
AutoMapper.CreateMap<Price,PriceViewModel>();
The AutoMapper would then determine the mappings of the subcomposita lists automatically. 然后,AutoMapper将自动确定子组合列表的映射。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.