我有一个Order对象,它有一个OrderLine对象列表和一个OrderLm对象,它有一个OrderLineVm对象列表。 OrderLine对象具有OrderLineVm对象中不存在的ValueB字段。
我遇到的问题是,AutoBper将ValueB设置为null,即使我告诉它忽略此属性:
[TestFixture]
public class AutomapperDestinationIssueTest2
{
[Test]
public void OrderLineValueBShouldNotBeNull()
{
Mapper.CreateMap<OrderVm, Order>().ForMember(dest => dest.Lines, opt => opt.UseDestinationValue());
Mapper.CreateMap<OrderLineVm, OrderLine>()
.ForMember(dest => dest.ValueB, opts => opts.Ignore());
var orderVm = new OrderVm() { Id = 1 };
orderVm.Lines.Add(new OrderLineVm() { ValueA = "New ValueA"} );
var order = new Order() { Id = 1 };
order.Lines.Add(new OrderLine() { ValueA = "Old ValueA", ValueB = "Old ValueB " });
Mapper.Map(orderVm, order);
Assert.IsNotNull(order.Lines[0].ValueB); // Fails. ValueB is null here.
}
public class OrderLine
{
public string ValueA { get; set; }
public string ValueB { get; set; }
}
public class OrderLineVm
{
public string ValueA { get; set; }
}
public class Order
{
public int Id { get; set; }
public List<OrderLine> Lines { get; set; }
public Order()
{
Lines = new List<OrderLine>();
}
}
public class OrderVm
{
public int Id { get; set; }
public List<OrderLineVm> Lines { get; set; }
public OrderVm()
{
Lines = new List<OrderLineVm>();
}
}
}
我缺少什么?
答案 0 :(得分:2)
为地图创建添加一个额外的映射,从列表到列表的地图开始工作。
Mapper.CreateMap<OrderVm, Order> ().ForMember(dest => dest.Lines, opt => opt.UseDestinationValue());
Mapper.CreateMap<List<OrderLineVm>,List<OrderLine>> ();
Mapper.CreateMap<OrderLineVm, OrderLine> ().ForMember (d => d.ValueB, opt => opt.Ignore());