2015-08-27 45 views
1

假設我有以下結構:Automapper映射屬性

public class EntityDto 
{ 
    int EntityId { get; set; } 
} 

public class Entity 
{ 
    EntityId<int> EntityId { get; } 
} 

public class EntityId<T> 
{ 
    T Id { get; set; } 
} 

什麼是在這種情況下定義映射輪廓的適當方法?當然,這兩個方向都是。 任何幫助將不勝感激。

+0

我在想方向 - 你想映射'EntityId '到'Entity'到'EntityDto'並且向後? – Kamo

回答

1

假設,你的類是這樣的:

class EntityDto 
{ 
    public int EntityId { get; set; } 
} 

class EntityId<T> 
{ 
    public T Id { get; set; } 
} 

class Entity 
{ 
    public EntityId<int> EntityId { get; set; } 
} 

映射將是這樣的:

static void CreateMapForEntityId<T>() 
    { 
     Mapper.CreateMap<T, EntityId<T>>() 
      .ForMember(_ => _.Id, options => options.MapFrom(_ => _)); 
    } 

    static void TestMapping(int id) 
    { 
     CreateMapForEntityId<int>(); 

     Mapper 
      .CreateMap<Entity, EntityDto>() 
      .ForMember(_ => _.EntityId, options => options.MapFrom(_ => _.EntityId.Id)) 
      .ReverseMap(); 

     Mapper.AssertConfigurationIsValid(); 

     var entity = new Entity { EntityId = new EntityId<int> { Id = id } }; 

     var entityDto = Mapper.Map<EntityDto>(entity); 
     Debug.Assert(entityDto.EntityId == id); 

     var entityClone = Mapper.Map<Entity>(entityDto); 
     Debug.Assert(entityClone.EntityId.Id == id); 
    } 

基本上不會有任何 「自動」 -mapping。

+0

這工作! 現在下面的異常被拋出: 類型「System.TypeLoadException」的第一次機會異常出現在mscorlib.dll 其他信息:方法「的GetEnumerator」在IEnumerable類型未實現。 結構如下: class UnauthorizedItemsDto InspectableItemDto [] PeerToPeerApplications {get;組; } } public interface IUnauthorizedItems { IEnumerable PeerToPeerApplications {get; } } –

+0

這個例外與問題無關。至少,在答案中不能使用代碼拋出。 – Dennis