首页 > 解决方案 > Automapper:映射子对象(对象列表)从数据库获取数据

问题描述

我有这些课程:

public class Tournament
{
  public int Id { get; set; }
  public List<Prize> Prizes { get; set; }
  ...
}

public class Prize
{
    public int Id { get; set; }
    public int RankPosition { get; set; }
    public Stuff PrizeStuff { get; set; }
}

public class Stuff
{
    public int Id { get; set; }
    public string Description{ get; set; }
    public string StuffImagine { get; set; }    
}

一个锦标赛级别可以有多个列表形式的奖项;一个奖项与锦标赛相关联,RankPosition 是获胜者(设置为 1)、第二名和第三名。STUFF 是一个 sql server 表,其中注册了“RankedPosition”在锦标赛中获胜的所有项目。

我的问题是填充对象 STUFF 只提供来自客户端的 ID。

来自客户端的 json 是这样的:

{
  "Name":"Test",
  "Rule": "this is a rule",
      "OtherProperty": "Just another property",
  "PrizePool":
  [
    {
        "RankPosition": "0",
        "Prize": 
        {
            "ID": 1
        }
    },
        {
        "RankPosition": "1",
        "Prize": 
        {
            "ID": 2
        }
    },
        {
        "RankPosition": "2",
        "Prize": 
        {
            "ID": 3
        }
    }
  ]
}

在这种情况下,我想使用上面的客户端 JSON 设置我的 STUFF 类对象并将 STUFF 对象保存到 db。

我如何从 SOURCETOURNMENT 类调用 CreateMap 方法到 TORUNAMENT 以使 PRIZES 列表可以映射来自 db 的内部对象 STUFF?

源和目标 PRIZES 对象是相同的。

更新:我尝试按照建议使用 Automapper.Collection,但我不知道该怎么做。这是真正的代码:

// SOURCE
public class TournamentParameters
{
    public string Name { get; set; }
    public List<PremioGiocatore> Montepremi { get; set; }
    ... Other props
}

// DESTINATION
public class DataTournamentParameters
{
    public string Name { get; set; }
    public List<PremioGiocatore> Montepremi { get; set; }
    ... Other props
}

// Prize for the first & second in the tournament
public class PremioGiocatore
{
    public int Id { get; set; }
    public PosizioneClassifica PosizioneClassifica { get; set; }
    public Premio Premio { get; set; }
}

// Registry of Prizes
public class Premio
{
    public int Id { get; set; }
    public string Descrizione { get; set; }
}

在 Api 的启动中,我有映射器配置:

Mapper.Initialize((cfg) =>
{
    cfg.AddCollectionMappers();
    cfg.SetGeneratePropertyMaps<GenerateEntityFrameworkPrimaryKeyPropertyMaps<Contesto>>();
}); 

我尝试将源对象映射到目标对象:

public int Create(TournamentParameters info)
{
    DataTournamentParameters dataInfo = _mapper.Map<TournamentParameters, DataTournamentParameters>(info);
    ...
}   

由于 Source 和 Destination 基本上是相等的,我不知道如何创建地图以允许从仅具有 ID 的源开始填充我的 List 目的地,如上所述。

标签: c#entity-frameworkautomapper

解决方案


推荐阅读