automapper:映射复杂的源类tocomplex派生类

时间:2016-11-24 15:10:10

标签: c# model-view-controller automapper

    [DataContract]
    public class SupplierView : BaseView
    {   
        [DataMember]
        Public int SupplierId { get; set; }
        [DataMember]
        Public ApprovedSupplierView approvedSupplier { get; set; }
        [DataMember]
        Public AdHocSupplierView adhocsupplier { get; set; }
        //other fields...
    }
    [DataContract]
    public class ContextSupplierView : SupplierView //Working
    {   
        [DataMember]
        Public int SupplierId { get; set; }
        //New fields added
        [DataMember]
        Public ContextApprovedSupplierView contextApprovedSupplier { get; set; }
        [DataMember]
        Public ContextAdHocSupplierView contextAdhocsupplier { get; set; }
        //other fields...
    }
    public class ApprovedSupplierView :  BaseView
    {   
        [DataMember]
        Public string Name { get; set; }
        [DataMember]
        Public string Phone { get; set; }




    [DataContract]
    public class ContextSupplierView : SupplierView //Not working
    {   
        [DataMember]
        Public int SupplierId { get; set; }
        [DataMember]
        Public new ContextApprovedSupplierView approvedSupplier { get; set; }
        [DataMember]
        Public new ContextAdHocSupplierView adhocsupplier { get; set; }
        //other fields...
    }

    [DataContract]
    public class ContextApprovedSupplierView :  ApprovedSupplierView
    {   
        [DataMember]
        Public string ContextDescription { get; set; }

    SupplierView supplierObject = new SupplierView(Linq populates this correctly);
    Mapper.CreateMap<SupplierView, ContextSupplierView>();
    claimContext.Supplier = Mapper.Map<ContextSupplierView>(supplierObject);

我有一个项目已经从数据库中获取了供应商及其嵌套类型,但我如何使用automapper将所有内容复制到ContextSupplier中,该供应商具有ContextApprovedSupplier approvedSupplier和ContextAdHocSupplier adHocSupplier但是它给出了:

  

缺少类型映射配置或不支持的映射。

     

映射类型:ApprovedSupplierView - &gt; ContextApprovedSupplierView   TotalSystemsPlc.Bluescape.Claims.DataContracts.Views.ProjectLoadViews.ApprovedSupplierView    - &GT; TotalSystemsPlc.Bluescape.Claims.DataContracts.Views.ContextViews.ContextApprovedSupplierView

     

目的地路径:   ContextSupplierView.ApprovedSupplier.ApprovedSupplier

     

来源价值:   TotalSystemsPlc.Bluescape.Claims.DataContracts.Views.ProjectLoadViews.ApprovedSupplierView

如果我创建新字段contextApprovedSupplier和contextAdhocsupplier,它会自动填充ApprovedSupplier和Adhocsupplier,它们可以单独映射,但我宁愿在一个命令中完成所有操作。 任何帮助都会得到很好的收获,因为我已经尝试了几个小时来做​​到这一点!!!

编辑:道歉,请立即找到正确的层次结构!

1 个答案:

答案 0 :(得分:0)

enter image description here

@Rafal将映射添加到一起真的很有用,非常感谢!

Mapper.CreateMap<SupplierView, ContextSupplierView>();
Mapper.CreateMap<ApprovedSupplierView, ContextApprovedSupplierView>();
Mapper.CreateMap<AdHocSupplierView, ContextAdHocSupplierView>();

我还必须添加一个默认构造函数,因为它会发出一个引用缺失强制转换的错误!我期待现在更多地使用Automapper。