[英]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 --
}
上面是我的POCO類,而我剛開始使用Automapper
。 我沒有什么復雜的關系。 我對我的source
類是什么類以及如何進行映射感到困惑。
因為我只想擁有。
為了清楚起見,我希望將它們顯示為以下形式:
Name : Snack bar
Price : $1.00
Stocks :
Storages | How many
Storage1 | 23
Storage2 | 24
Storage3 | 10
到目前為止,我只能是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));
然后像這樣存儲它們:
var items = _itemService.All.Project().To<ItemDTO>();
簡而言之,如何為其余屬性成員進行映射? 有小費嗎? 演示代碼會很棒。 非常感謝!
這是一個要添加到我的評論中的示例。
假設您有這些課程
模型
public class Item
{
public string Name { get; set; }
public virtual ICollection<Stock> Stocks { get; set; }
public virtual ICollection<Price> Prices { get; set; }
}
視圖模型
public class ItemViewModel
{
public string Name { get; set; }
public StockViewModel [] Stocks { get; set; }
public PriceViewModel [] Prices { get; set; }
}
您只需要像下面這樣配置Automapper:
AutoMapper.CreateMap<Item,ItemViewModel>();
AutoMapper.CreateMap<Stock,StockViewModel>();
AutoMapper.CreateMap<Price,PriceViewModel>();
然后,AutoMapper將自動確定子組合列表的映射。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.