I'm getting the following error when trying to do a projection of a grouped query, that is grouped by two properties, using Automapper

Missing map from IGrouping`2 to PlayerWarScore. Create using Mapper.CreateMap<IGrouping`2, PlayerWarScore>

I'm currently trying something like this, which works fine if PlayerWar is an entity property of Score

Mapper.CreateMap<IGrouping<PlayerWar, Score>, PlayerWarScore>
    .ForMember(model => model.PlayerName, model => model.MapFrom(grouping => grouping.Key.Player.Name))
    .ForMember(model => model.WarName, model => model.MapFrom(grouping => grouping.Key.War.Name)),
    .ForMember(model => model.Score, model => model.MapFrom(grouping => grouping.Sum(score => score.Score));

But when PlayerWar is not an entity, but a model created just to hold a combined key made of two entities as below, then I get the error

public class PlayerWar
{
    public Player Player { get; set; }
    public War War { get; set; }
}

As an example, what I'm trying to achieve is, given the following EF6 entities.

public class Score
{
    public Player Player { get; set; }
    public Battle Battle { get; set; }
    public int Score { get; set; }
}

public class Player
{
    public string Name { get; set; }
}

public class Battle
{
    public string Name { get; set; }
    public War War { get; set; }
}

public class War
{
    public string Name { get; set; }
}

and another model that I wish to project them to

public class PlayerWarScore
{
    public string PlayerName { get; set; }
    public string WarName { get; set; }
    public int Score { get; set; }
}

How would I achieve the following query using Automapper's Project().To<PlayerWarScore>()?

context.Scores
    .GroupBy(score => new {score.Player, score.Battle.War})
    .Select(grouping => new PlayerWarScore {
        PlayerName = grouping.Key.Player.Name,
        WarName = grouping.Key.War.Name,
        Score = grouping.Sum(score => score.Score)
    })
    .ToList()

I get the feeling I'm approaching it the wrong way or missing an obvious Linq feature that would make it simple. I've tried including mappings for the entities to the combined key model and other shots in the dark, but so far wihtout any luck.

1

There are 1 best solutions below

5
On BEST ANSWER

In order to make your mapping work, you need to use PlayerWar as a GroupBy key rather than anonymous type (new {score.Player, score.Battle.War}) as you do currently:

context.Scores
    .GroupBy(score => new PlayerWar { Player = score.Player, War = score.Battle.War })
    .ProjectTo<PlayerWarScore>()
    .ToList();