2011-11-21 41 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