2011-11-21 48 views
1

非标准继承映射我在我的DB(其中后人引用与外键基地)“表继承”,使用的LINQ to SQL作为我DAL:与AutoMapper

[Table] 
class Document { 
    [Column]public int ID { get; set; } 
    [Column]public int DocTypeID { get; set; } 
    [Association]public Application Application { get; set; } 
} 

[Table] 
class Application { 
    [Column]public int ID { get; set; } 
    [Column]public string AppType { get; set; } 
    [Association]public Document Document {get;set} 
} 

因为L2S不支持多表继承Application不是从Document继承。然而,在我的实体类我也想继承:

class DocumentBase { 
    public int ID { get; set; } 
    public int DocTypeID { get; set; } 
} 

class MyApplication : DocumentBase { 
    public string AppType { get; set; } 
} 

现在,我创建的映射:

Mapper.CreateMap<Document, DocumentBase>(); 
Mapper.CreateMap<Application, MyApplication>(); 

但AutoMapper抱怨没有映射在MyApplication基本属性。我不想在MyApplication地图中复制基本属性(太多的DocumentBase后代)。我发现很少有帖子建议自定义ITypeConverter,但不明白如何将其应用于我的场景。我该怎么办?

回答

1

发现这个solution也遭受抱怨基本属性没有被映射,但略微修改了它:

static void InheritMappingFromBaseType<S, D>(this IMappingExpression<S, D> mappingExpression) 
    where S: Document 
    where D: DocumentBase 
{ 
    mappingExpression // add any other props of Document 
     .ForMember(d => d.DocTypeId, opt => opt.MapFrom(s => s.Document.DocTypeId); 
} 

否W¯¯它可以链接到每个DocumentBase后裔地图:

Mapper.CreateMap<Application, MyApplication>() 
    .InheritMappingFromBaseType(); 

AssertConfigurationIsValid()是幸福的。

+0

非常有趣,我以前没见过 – boca

2

问题是DocTypeId没有被映射。试试这个

Mapper.CreateMap<Document, DocumentBase>(); 
    Mapper.CreateMap<Application, MyApplication>() 
      .ForMember(d => d.DocTypeId, opt => opt.MapFrom(s => s.Document.ID); 

编辑后评论:

你可以从AssertConfigurationIsValid()调用基映射器这样

Mapper.CreateMap<Document, DocumentBase>(); 
    Mapper.CreateMap<Application, MyApplication>() 
    .AfterMap((app, myApp) => Map<Document, DocumentBase>(app.Document, myApp); 
+0

正是!我不想在每个后代中映射所有基础道具(如果在DocumentBase中有12个道具,并且我有8个继承自它的类)?所以我需要一些通用解决方案。 – UserControl

+0

看到我编辑的回复 – boca

+0

谢谢,它确实有效!然而,Mapper.AssertConfigurationIsValid()似乎并不知道AfterMap()说基础道具没有映射:(我不能禁用验证,因为它是测试的重要部分(在项目中太多的映射方式)。 – UserControl