【发布时间】: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