Anton Z
Anton Z

Reputation: 13

Automapper projection

i have question about Automapper projection. I have entity:

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

    public DateTime Date { get; set; }

    public string Price { get; set; }
}

And dto:

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

    public int Month { get; set; }

    public string TotalPrice { get; set; }
}

How can I create next projection with automapper

  var data = new List<SomeEntity>().AsQueryable()
        .GroupBy(p => new
        {
            p.Date.Month,
            p.Name
        }).Select(p => new
        {
            p.Key.Month,
            p.Key.Name,
            TotalPrice = p.Sum(entity => entity.Price)
        })
       .ToList()
       .Select(p => new SomeDto
        {
            Month = p.Month,
            Name = p.Name, 
            TotalPrice = p.TotalPrice
        });

Upvotes: 0

Views: 436

Answers (1)

Jimmy Bogard
Jimmy Bogard

Reputation: 26765

You can't - AutoMapper LINQ projections won't really work with intermediate anonymous types that you've created. In your first Select, you should remove the anonymous type:

var data = new List<SomeEntity>().AsQueryable()
    .GroupBy(p => new
    {
        p.Date.Month,
        p.Name
    }).Select(p => new SomeDto
    {
        Month = p.Key.Month,
        Name = p.Key.Name,
        TotalPrice = p.Sum(entity => entity.Price)
    })
   .ToList();

Then you don't need the second Select. You're already manually projecting so AutoMapper won't help you there.

Upvotes: 2

Related Questions