【问题标题】:Unexpected behavior AutoMapper mapping nested collection意外行为 AutoMapper 映射嵌套集合
【发布时间】:2016-01-07 11:37:49
【问题描述】:

我正在尝试使用 Mapper.Map(from, to); 映射具有嵌套集合的类型;我遇到了很多问题。

最初我遇到的问题是我的目标字段上的一个属性在我的源类型中不存在

 int Id {get; set; }

无论我使用什么 ForMember 映射(Ignore() 或 UseDestinationValue()),都始终设置为 0。我发现我必须为我的集合类型创建一个映射:

Mapper.CreateMap(List<source>, List<destination>)

这导致 id 字段未设置为 0,但现在我的源集合中的所有值都不再复制到我的目标集合。下面是我的意思的一个例子:

public class TestModel
{
    public virtual List<NestedTestModel> Models { get; set; }
}

public class NestedTestModel
{
    public int Value { get; set; }
}

public class TestEntity
{
    public int Id { get; set; }
    public virtual List<NestedTestEntity> Models { get; set; }
}

public class NestedTestEntity
{
    public int Id { get; set; }
    public int Value { get; set; }
}

[Test]
public void TestMappingFromCalibrationModelToCalibrationModelEntity()
{
    Mapper.CreateMap<TestModel, TestEntity>()
        .ForMember(x => x.Id, x => x.UseDestinationValue());
    Mapper.CreateMap<NestedTestModel, NestedTestEntity>()
        .ForMember(x => x.Id, x => x.UseDestinationValue())
        .ForMember(x => x.Value, y => y.MapFrom(z => z.Value));
    Mapper.CreateMap<List<NestedTestModel>, List<NestedTestEntity>>();

    TestModel from = new TestModel();
    from.Models = new List<NestedTestModel>
    {
        new NestedTestModel { Value = 3 }
    };

    TestEntity to = new TestEntity
    {
        Models = new List<NestedTestEntity>
        {
            new NestedTestEntity { Id = 1, Value = 2 }
        }
    };

    var actual = Mapper.Map<TestModel, TestEntity>(from, to);

    // this only works if Mapper.CreateMap<List<NestedTestModel>, List<NestedTestEntity>>();
    Assert.AreEqual(1, actual.Models[0].Id);

    // Results in 
    // Expected: 3
    // But was:  2
    Assert.AreEqual(3, actual.Models[0].Value); 

}

【问题讨论】:

    标签: c# entity-framework mapping automapper


    【解决方案1】:

    AutoMapper 支持集合所以

    Mapper.CreateMap(List<source>, List<destination>);
    

    不是必需的。

    您只需要:

    Mapper.CreateMap<sourceNested, destinationNested>();
    Mapper.CreateMap<source, destination>();
    

    然后像这样映射:

    var res = Mapper.Map<IEnumerable<source>, IEnumerable<destination>>(source);
    

    当将TestModel 映射到TestEntity TestEntity.Id 时,将始终0,因为它的类型是intint 的默认值是0

    【讨论】:

    • 好的,我假设通过使用 Mapper.Map(from, to);它将保留目标中未映射属性的值
    猜你喜欢
    • 2020-12-12
    • 2017-06-11
    • 1970-01-01
    • 1970-01-01
    • 2020-07-17
    • 1970-01-01
    • 2017-07-20
    • 2020-02-04
    • 1970-01-01
    相关资源
    最近更新 更多