开发者

How to map a virtual property without mapping it explictly for each derived class that overrides the property using AutoMapper?

I'm mapping my entities to DTOs, using AutoMapper. Some of my entities have virtual properties that may be overridden by derived entities. I'm mapping the virtual properties using the base classes they're defined in. However, when mapping the derived classes, AutoMapper maps the base implementation of the virtual properties instead of the overridden one.

I'll start with the class definitions:

public class BaseType
{
    public virtual string Title
    {
        get { return string.Empty; }
    }    
}

public class DerivedType : BaseType
{
    public override string Title
    {
        get { return Name; }
    }    

    public string Name { get; set; }
}

public class BaseTypeDto
{
    public string Title { get; set; }    
}

public class DerivedTypeDto : BaseTypeDto
{
    public string Name { get; set; }    
}

Now for the mapping configuration:

CreateMap<BaseType, BaseTypeDto>()
    .ForMember(n => n.Title, p => p.MapFrom(q => q.Title ?? "-"))
    .Include<DerivedType, DerivedTypeDto>();

CreateMap<DerivedType, DerivedTypeDto>()

And finally the mapping:

DerivedTypeDto dto = Mapper.Map<DerivedType, DerivedTypeDto>(instance);

When I put the Title mapping on the CreateMap call that configures the derived type, it works. But since I have about 20 derived types, I really want the Title mapping to be configured on the base class, 开发者_如何学Cnot having to repeat it for each derived class.

Is this possible with AutoMapper?


Could you not use the ConstructUsing() option? This would allow you to have a delegate to map to the base class object all the time?

CreateMap<basetype, baseTypeDto>()
    .ConstructUsing(y => base.title = basetype.title);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜