自动映射器 - 将派生类映射到 dto



>我试图将从基类继承的类映射到dto。

public class LaunchConfiguration : Document
{
public string Brand { get; set; }
public string SettingName{ get; set; }
}
public class LaunchConfigurationDto
{
public string Brand { get; set; }
public string SettingName{ get; set; }
}

dto 的要点是在基本文档返回给用户时隐藏其字段。这是我的地图配置

public class DtoProfile : Profile
{
public DtoProfile()
{
CreateMap<LaunchConfiguration,LaunchConfigurationDto>();
}
};

我遇到的问题是自动映射器抱怨未映射的基类属性。"找到了未映射的成员。"这些属性是基类上的属性。我尝试在配置文件中指定要忽略它,但无济于事.任何人都可以指定正确的方法来执行此操作吗?

我的配置服务方法,以防有人想知道:

public void ConfigureServices(IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = Configuration["ApiInformation:Name"], Version = Configuration["ApiInformation:Version"] });
c.DescribeAllEnumsAsStrings();
});
services.AddAutoMapper(mc =>
{
mc.AddProfile(new DtoProfile());
});
services.AddMvc().AddJsonOptions(options =>
{
options.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
});
}

我的基类 :

public class Document : IDocument, IDocument<Guid>
{
public Document()
{
this.Id = Guid.NewGuid();
this.AddedAtUtc = DateTime.UtcNow;
}
/// <summary>The Id of the document</summary>
[BsonId]
public Guid Id { get; set; }
/// <summary>The datetime in UTC at which the document was added.</summary>
public DateTime AddedAtUtc { get; set; }
/// <summary>The version of the schema of the document</summary>
public int Version { get; set; }
}

我的实现_mapper是我的注入映射器,_repo我的注入存储库。映射方法调用上发生异常

Task ILaunchConfigurationService<LaunchConfigurationDto >.InsertLaunchConfiguration(LaunchConfigurationDto model)
{
var mapped =  _mapper.Map<LaunchConfiguration >(model);
return _repo.AddOneAsync(mapped);
}

你的问题应该通过简单地将 ReverseMap(( 添加到 CreateMap 调用来解决:

public class DtoProfile : Profile
{
public DtoProfile()
{
CreateMap<LaunchConfiguration, LaunchConfigurationDto>().ReverseMap();
}
};

默认情况下,自动映射器创建单向地图。反向映射只是用于创建反向映射的糖,以防以一种方式没有特殊的映射。你也可以这样做:

public class DtoProfile : Profile
{
public DtoProfile()
{
CreateMap<LaunchConfiguration, LaunchConfigurationDto>();
CreateMap<LaunchConfigurationDto, LaunchConfiguration>();
}
};

您可以在文档中阅读有关此内容的更多信息

但是,我不能向您保证,在提交更改时,您当前的实现不会遇到数据库的异常。

最新更新