简体   繁体   English

自动映射器映射属性

[英]Automapper mapping properties

Suppose I have the following structure: 假设我具有以下结构:

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

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

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

What is the appropriate way for defining the mapping profile in this case? 在这种情况下,定义映射配置文件的适当方法是什么? Both directions, of course. 当然是双向的。 Any help will be greatly appreciated. 任何帮助将不胜感激。

Assuming, that your classes look like this: 假设您的类如下所示:

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

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

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

mapping will look like this: 映射将如下所示:

    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);
    }

Basically, there won't be any "auto"-mapping. 基本上,不会有任何“自动”映射。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM