c# - Automapper 不映射基础

标签 c# automapper

您好,我在 automapper 中进行映射时遇到了一些问题。

我有 2 个 DTO BaseDto 和 BaseOrganizationDto

public class BaseDto
{}

public class SensitiveBaseDto : BaseDto
{}

我使用以下映射:

CreateMap<IEntity, BaseDto>()
                .Include<IEntity, SensitiveBaseDto>()
                .IncludeBase<IEntity, BaseDto>();

我尝试根据一些逻辑来获取某个 dto

public BaseDto MapToDto(Guid asSeenById, IEntity entity)
    if (entity.Id != asSeenById)
    {
      return this.MapToDto<BaseDto>(entity);
    }
    return this.MapToDto<SensitiveBaseDto>(entity);
}

但它总是返回一个 SensitiveBaseDto,我已经验证了 MapToDto 方法中的逻辑是否正确执行。

我错过了什么?

最佳答案

通过这样做解决了它:

public override TDtoType MapToDto<TDtoType>(IEntity entity)
{
    var dto = typeof(TDtoType) == typeof(SensitiveDto) 
        ? new SensitiveDto() 
        : new BaseDto();

    this.Engine.Map(entity, dto);
    return dto as TDtoType;
}

关于c# - Automapper 不映射基础,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32332205/

相关文章:

c# - 带有 DbContext 多级 Include() 的 AutoMapper ProjectTo

c# - 哪种方法最好? AutoMapper 反对隐式(C# 引用)

c# - 在 Windows 资源管理器中将文件从(例如)iPhone 拖放到 WPF 应用程序中

c# - 如何访问继承的值

c# - 使用 Automapper 覆盖现有映射

unit-testing - 如何使用 StructureMap 依赖注入(inject)在 Web API 测试中模拟 AutoMapper IMapper 对象?

c# - .Net Core 解决方案中每个项目的 Automapper 不同配置文件

c# - 无法使用 HTTP POST 上传文件

c# - 使用 iTextSharp 创建 PDF 时放置页码

c# - 如何将 TestScheduler 与 ReplaySubject 时间窗一起使用