Tôi có một dự án sử dụng AutoMapper 3.1.1, tôi đã có thể cách ly vấn đề tôi đang gặp phải.Tại sao Ánh xạ bất ngờ xảy ra trong AutoMapper?
Dưới đây là các lớp học thử nghiệm của tôi:
class BaseClass
{
public string PropertyA { get; set; }
}
class DerivedClass: BaseClass
{
public string PropertyB { get; set; }
}
class ContainerClass
{
public DerivedClass ComplexProperty { get; set; }
public string PropertyC { get; set; }
}
class SourceClass
{
public string PropertyA { get; set; }
public string PropertyB { get; set; }
public string PropertyC { get; set; }
}
Dưới đây là quy tắc ánh xạ của tôi:
Mapper.CreateMap<SourceClass, ContainerClass>()
.ForMember(d => d.ComplexProperty, o => o.MapFrom(s => Mapper.Map<DerivedClass>(s)))
.AfterMap((s, d) => System.Diagnostics.Debug.WriteLine("SourceClass-> ContainerClass mapped"));
Mapper.CreateMap<SourceClass, DerivedClass>()
.AfterMap((s, d) => System.Diagnostics.Debug.WriteLine("SourceClass -> DerivedClass mapped"));
Mapper.CreateMap<BaseClass, DerivedClass>()
.AfterMap((s, d) => System.Diagnostics.Debug.WriteLine("BaseClass -> DerivedClass mapped"));
Đây là mã của tôi:
var source = new SourceClass {
PropertyA = "ValueA",
PropertyB = "ValueB",
PropertyC = "ValueC",
};
var destination = Mapper.Map<ContainerClass>(source);
Console.WriteLine("PropertyA: " + destination?.ComplexProperty?.PropertyA);
Console.WriteLine("PropertyB: " + destination?.ComplexProperty?.PropertyB);
Console.WriteLine("PropertyC: " + destination?.PropertyC);
Đầu ra là:
PropertyA: ValueA
PropertyB:
PropertyC: ValueC
Tôi mong đợi PropertyB có giá trị "ValueB", nhưng thay vào đó nó có giá trị null. Nó xảy ra, bởi vì người lập bản đồ từ BaseClass đến DerivedClass thực thi vì một lý do nào đó. Đầu ra gỡ lỗi của tôi như sau:
SourceClass -> DerivedClass mapped
BaseClass -> DerivedClass mapped
SourceClass -> ContainerClass mapped
Tại sao AutoMapper thực thi ánh xạ BaseClass -> DerivedClass?
UPDATE: Thank để Marius bây giờ tôi biết rằng ánh xạ từ BaseClass để DerivedClass không hợp lệ. Tôi không thể loại bỏ quy tắc lập bản đồ này như anh ta đề xuất, bởi vì tôi cần nó cho ứng dụng của tôi. Theo ngoại lệ, tôi đã thêm Ignore cho PropertyB:
Mapper.CreateMap<BaseClass, DerivedClass>()
.ForMember(d => d.PropertyB, o => o.Ignore())
.AfterMap((s, d) => System.Diagnostics.Debug.WriteLine("BaseClass -> DerivedClass mapped"));
Bây giờ Mapper.AssertConfigurationIsValid();
không ném ngoại lệ nữa. Nhưng câu hỏi ban đầu vẫn đứng vững. Tại sao AutoMapper thực thi ánh xạ BaseClass -> DerivedClass?
Tôi đã cập nhật câu hỏi của mình. Tôi không thể chỉ cần loại bỏ BaseClass -> DerivedClass, tôi cần nó cho ứng dụng của tôi. –