.net 使用AutoMapper的非标准继承映射

.net 使用AutoMapper的非标准继承映射,.net,linq-to-sql,inheritance,mapping,automapper,.net,Linq To Sql,Inheritance,Mapping,Automapper,我在数据库中有“表继承”(其中子体使用外键引用base),并使用Linq To Sql作为DAL: [Table] class Document { [Column]public int ID { get; set; } [Column]public int DocTypeID { get; set; } [Association]public Application Application { get; set; } } [Table] class Applicati

我在数据库中有“表继承”(其中子体使用外键引用base),并使用Linq To Sql作为DAL:

[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不支持多表继承,
应用程序
不从
文档
继承。但是,在实体类中,我确实希望继承:

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>();
Mapper.CreateMap();
CreateMap();

但AutoMapper抱怨
MyApplication
中的基本属性未映射。我不想复制
MyApplication
map中的基属性(来自
DocumentBase
的子体太多)。我发现很少有帖子建议定制
ITypeConverter
,但不知道如何将其应用到我的场景中。我该怎么办?

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

    Mapper.CreateMap<Document, DocumentBase>();
    Mapper.CreateMap<Application, MyApplication>()
          .ForMember(d => d.DocTypeId, opt => opt.MapFrom(s => s.Document.ID);
Mapper.CreateMap();
Mapper.CreateMap()
.ForMember(d=>d.DocTypeId,opt=>opt.MapFrom(s=>s.Document.ID);
评论后编辑:

您可以像这样调用基本映射器

Mapper.CreateMap<Document, DocumentBase>();
    Mapper.CreateMap<Application, MyApplication>()
    .AfterMap((app, myApp) => Map<Document, DocumentBase>(app.Document, myApp);
Mapper.CreateMap();
Mapper.CreateMap()
.AfterMap((app,myApp)=>Map(app.Document,myApp);
发现此问题,并且
资产配置验证()
抱怨未映射基本属性,但对其进行了轻微修改:

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);
}

而且,
assertconfigurationsvalid()
很高兴。

没错!而且我不想映射每个后代中的所有基本道具(如果DocumentBase中有12个道具,我从中继承了8个类怎么办?),所以我需要一些通用解决方案。谢谢,它确实有效!但是,Mapper.assertconfigurationsvalid()似乎不知道AfterMap()说基本道具没有映射:(我不能禁用验证,因为它是测试的重要部分(项目中的映射太多)。我明白了。另一种让AssertConfigurationsValid满意的方法是显式忽略基本属性,如:Mapper.CreateMap().FormMember(d=>d.DocTypeId,opt=>opt.ignore()).AfterMap((app,myApp)=>Map(app.Document,myApp);非常有趣。我以前没见过这个
Mapper.CreateMap<Application, MyApplication>()
    .InheritMappingFromBaseType();