【问题标题】:Automapper mapping propertiesAutomapper 映射属性
【发布时间】:2015-08-27 06:58:55
【问题描述】:

假设我有以下结构:

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

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

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

在这种情况下,定义映射配置文件的适当方法是什么? 两个方向,当然。 任何帮助将不胜感激。

【问题讨论】:

  • 我想知道方向 - 你想映射 EntityId&lt;T&gt;EntityEntityDto 并向后?

标签: c# automapper dto


【解决方案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);
    }

基本上,不会有任何“自动”映射。

【讨论】:

  • 这成功了!现在引发以下异常: mscorlib.dll 中发生了“System.TypeLoadException”类型的第一次机会异常附加信息:IEnumerable 类型中的方法“GetEnumerator”未实现。结构如下: class UnauthorizedItemsDto { InspectableItemDto[] PeerToPeerApplications { get;放; } } 公共接口 IUnauthorizedItems { IEnumerable PeerToPeerApplications { get; } }
  • 此异常与问题无关。至少,它不能在答案中使用代码抛出。
猜你喜欢
  • 2020-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多