2013-04-12 52 views
1

我有一個EntityDtos的集合。AutoMapper和基本類型

每個EntityDto都有一個名爲EntityType的屬性。

每個EntityTypes對應於不同的子類,像這樣

abstract class EntityBase { EntityType = EntityType.Base; } 
class EntityOne : EntityBase { EntityType = EntityType.One; } 
class EntityTwo : EntityBase { EntityType = EntityType.Two; } 

我試圖映射到EntityBase的集合。 AutoMapper因錯誤「無法創建抽象類的實例」而失敗。我有Type枚舉,因此知道每個類型應映射到什麼類型......但實際上,只是希望它們都映射到我的EntityBase集合中。

我不知道這一點......

我有這個工作,但它是非常難看。

Mapper.CreateMap<EntityCollectionDto, EntityCollection>().ForMember(
    s => s.Entities, d => d.MapFrom(
     x => new List<EntityBase>(
      from p in x.Entitys 
      select p.EntityType == EntityType.One ? Mapper.Map<EntityOne>(p) as EntityBase 
       : p.EntityType == EntityType.Two ? Mapper.Map<EntityTwo>(p) as EntityBase 
       : Mapper.Map<EntityThree>(p) as EntityBase 
      ) 
     ) 
    ); 

Mapper.CreateMap<EntityDto, EntityOne>(); 
Mapper.CreateMap<EntityDto, EntityTwo>(); 

回答

2

我不知道你會喜歡這更好,但假設實體類如下:

public abstract class EntityBase 
{ 
    public EntityType EntityType { get { return EntityType.Base; } } 
} 
public class EntityOne : EntityBase 
{ 
    public new EntityType EntityType { get { return EntityType.One; } } 
} 
public class EntityTwo : EntityBase 
{ 
    public new EntityType EntityType { get { return EntityType.Two; } } 
} 
public class EntityThree : EntityBase 
{ 
    public new EntityType EntityType { get { return EntityType.Three; } } 
} 
public class EntityCollection 
{ 
    public IList<EntityBase> Entities { get; set; } 
} 

public class EntityDto 
{ 
    public EntityType EntityType { get; set; } 
} 
public class EntityCollectionDto 
{ 
    public IList<EntityDto> Entities { get; set; } 
} 

您可以創建一個TypeConverter

public class EntityTypeConverter : AutoMapper.TypeConverter<EntityDto, EntityBase> 
{ 
    protected override EntityBase ConvertCore(EntityDto source) 
    { 
     switch (source.EntityType) 
     { 
      case EntityType.One: 
       return AutoMapper.Mapper.Map<EntityOne>(source); 
      case EntityType.Two: 
       return AutoMapper.Mapper.Map<EntityTwo>(source); 
      default: 
       return AutoMapper.Mapper.Map<EntityThree>(source); 
     } 
    } 
} 

然後這將簡化您的映射到:

AutoMapper.Mapper.CreateMap<EntityDto, EntityBase>() 
    .ConvertUsing(new EntityTypeConverter()); 

AutoMapper.Mapper.CreateMap<EntityDto, EntityOne>(); 
AutoMapper.Mapper.CreateMap<EntityDto, EntityTwo>(); 
AutoMapper.Mapper.CreateMap<EntityDto, EntityThree>(); 

AutoMapper.Mapper.CreateMap<EntityCollectionDto, EntityCollection>(); 

AutoMapper.Mapper.AssertConfigurationIsValid(); 

所以你仍然在TypeConverter(我不知道有一種方法可以避免這種情況)的具體映射,但我認爲最終的結果是一個更清潔。

+0

同意,我會考慮改變它。謝謝。 – CaffGeek