Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper collections

Tags:

automapper

I've read countless other posts and can't seem to figure out what's going on so it's time for some help.

I'm trying to map my domain entities which contain collections to dtos also containing collections.

Here's a primitive example; (i apologize in advance for the wall of code, i tried to keep it as short as possible):

Entities

public class Foo
{
    public Foo()
    {
        Bars = new List<Bar>();
    }
    public string Foo1 { get; set; }
    public ICollection<Bar> Bars { get; set; }
}
public class Bar
{
    public string Bar1 { get; set; }
}

Dtos

public class FooDto
{
    public FooDto()
    {
        Bars = new List<BarDto>();
    }
    public string Foo1 { get; set; }
    public IEnumerable<BarDto> Bars { get; set; }
}
public class BarDto
{
    public string Bar1 { get; set; }
}

Maps

Mapper.CreateMap<Foo, FooDto>();
Mapper.CreateMap<ICollection<Bar>, IEnumerable<BarDto>>();

Tests

// Arrange
var e = new Foo
{
    Foo1 = "FooValue1",
    Bars = new List<Bar>
    {
        new Bar
        {
             Bar1 = "Bar1Value1"
        },
        new Bar
        {
            Bar1 = "Bar2Value1"
        }
    }
};


// Act
var o = Mapper.Map<Foo, FooDto>(e);

// Assert

Mapper.AssertConfigurationIsValid();
Assert.AreEqual(e.Foo1, o.Foo1);
Assert.IsNotNull(o.Bars);
Assert.AreEqual(2, o.Bars.Count());

I'm not getting any configuration errors and Foo1 is mapping just fine.

o.Bars is a Castle.Core.Interceptor.IInterceptor[] and doesn't contain any of the values from my domain entity...

What am i missing here?

like image 455
David Wick Avatar asked Dec 21 '22 14:12

David Wick


1 Answers

Instead of:

Mapper.CreateMap<ICollection<Bar>, IEnumerable<BarDto>>();

try simply:

Mapper.CreateMap<Bar, BarDto>();

AutoMapper will take care of the rest.

like image 192
Darin Dimitrov Avatar answered Mar 27 '23 01:03

Darin Dimitrov