自动映射器:映射子对象(对象列表)从db

时间:2018-12-19 13:33:23

标签: c# entity-framework 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; }    
}

锦标赛课程可以列表形式获得多个奖项; 一个奖项与锦标赛相关,RanPosition为获胜者(设置为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。

如何从SOURCETOURNAMENT类到TORUNAMENT调用CreateMap方法 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);
    ...
}   

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

0 个答案:

没有答案
相关问题