2015-08-27 248 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