Automapper 集合

标签 automapper

我已经阅读了无数其他帖子,但似乎无法弄清楚发生了什么,所以是时候寻求帮助了。

我正在尝试将包含集合的域实体映射到也包含集合的 dtos。

这是一个原始示例; (我提前为代码墙道歉,我尽量保持简短):

实体

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; }
}

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

测试
// 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());

我没有收到任何配置错误,Foo1 映射得很好。

o.Bars 是一个 Castle.Core.Interceptor.IInterceptor[] 并且不包含来自我的域实体的任何值...

我在这里缺少什么?

最佳答案

代替:

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

简单地尝试:
Mapper.CreateMap<Bar, BarDto>();

AutoMapper will take care 的其余部分。

关于Automapper 集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5923700/

相关文章:

c# - 自动映射器 : how to eleminate repetitive mapping?

c# - 复制引用而不是新的深拷贝

c# - 自动映射器映射动态对象

c# - Automapper 异常 : "Missing type map configuration or unsupported mapping."

c# - 带有构造函数参数的自动映射对象

c# - Automapper 有时无法映射通过 ForMember 设置的属性

当非规范化子对象时,AutoMapper QueryableExtensions 抛出 NullReference

c# - 如何在自动映射器的可查询映射中为枚举创建映射?

automapper - 在 AutoMapper 问题中使用 string.Split()

c# - 使用 AutoMapper 将成员映射委托(delegate)给子对象