簡體   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