开发者

Automapper collections

开发者 https://www.devze.com 2023-03-03 11:38 出处:网络
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'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开发者_JAVA技巧 is a Castle.Core.Interceptor.IInterceptor[] and doesn't contain any of the values from my domain entity...

What am i missing here?


Instead of:

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

try simply:

Mapper.CreateMap<Bar, BarDto>();

AutoMapper will take care of the rest.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号