繁体   English   中英

如何在自动映射器中为具有复杂关系的类进行映射

[英]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

到目前为止,我只能是ItemNameItemPrice认为是这样的:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM