考虑这些课程:
class Master
{
public int Id { get; set; }
public ObservableCollection<Detail> Details
{
get
{
return details ?? (details = new ObservableCollection<Detail>());
}
}
private ObservableCollection<Detail> details;
}
class Detail
{
public int Id { get; set; }
public int MasterId { get; set; }
}
...以及一些使用Automapper 3.0或更高版本的代码:
Mapper.CreateMap<Master, Master>();
Mapper.CreateMap<Detail, Detail>();
Mapper.AssertConfigurationIsValid();
var original = new Master
{
Id = 1,
Details =
{
new Detail { Id = 1, MasterId = 1 },
new Detail { Id = 2, MasterId = 1 },
new Detail { Id = 3, MasterId = 1 },
}
};
var copy = Mapper.Map<Master>(original);
Console.WriteLine(copy.Details.Count); // outputs 0
现在,让我们改变Master
定义(用read-write替换只读,懒惰初始化的集合属性):
class Master
{
public int Id { get; set; }
public ObservableCollection<Detail> Details { get; set; }
}
...和示例代码(现在我们应该调用集合构造函数):
Mapper.CreateMap<Master, Master>();
Mapper.CreateMap<Detail, Detail>();
Mapper.AssertConfigurationIsValid();
var original = new Master
{
Id = 1,
Details = new ObservableCollection<Detail>
{
new Detail { Id = 1, MasterId = 1 },
new Detail { Id = 2, MasterId = 1 },
new Detail { Id = 3, MasterId = 1 },
}
};
var copy = Mapper.Map<Master>(original);
Console.WriteLine(copy.Details.Count); // outputs 3
在Automapper 3.0版之前,收集项已成功复制。
问题:
P.S。我已经问了类似的问题,但是没有回答,现在我可以发布一个代码,这会重现错误的行为。