c# - 继承配置文件的自动映射器在 json 中返回额外的属性
问题描述
根据我的阅读,标准是继承 Profile 类以便 Automapper 检测地图。https://automapper.org/
public class GamerVM : Profile
{
public GamerVM()
{
CreateMap<GamerVM, Gamer>();
CreateMap<Gamer, GamerVM>();
}
public int Id { get; set; }
public string Name { get; set; }
public string Tag { get; set; }
}
如果我在我的视图模型上继承这个类,则会返回带有额外属性的 Json:
{
"id": 8,
"name": "Ashton Heir",
"tag": "Legend",
"defaultMemberConfig": {
"nameMapper": {
"getMembers": {},
"namedMappers": [
{
"methodCaseSensitive": false
},
{},
{
"prefixes": [
"Get"
],
"postfixes": [],
"destinationPrefixes": [],
"destinationPostfixes": []
}
]
},
"memberMappers": [
{
"nameMapper": {
"getMembers": {},
"namedMappers": [
{
"methodCaseSensitive": false
},
{},
{
"prefixes": [
"Get"
],
"postfixes": [],
"destinationPrefixes": [],
"destinationPostfixes": []
}
]
}
},
{
"sourceMemberNamingConvention": {
"splittingExpression": {
"pattern": "(\\p{Lu}+(?=$|\\p{Lu}[\\p{Ll}0-9])|\\p{Lu}?[\\p{Ll}0-9]+)",
"options": 0
},
"separatorCharacter": ""
},
"destinationMemberNamingConvention": {
"splittingExpression": {
"pattern": "(\\p{Lu}+(?=$|\\p{Lu}[\\p{Ll}0-9])|\\p{Lu}?[\\p{Ll}0-9]+)",
"options": 0
},
"separatorCharacter": ""
}
}
]
}
我这样做正确吗?有没有办法让 JSON 忽略这些额外的属性?
解决方案
您的模型不应继承 Profile。您将 Profile 子类化以配置模型到模型的映射。
public class GamerMappingProfile : Profile
{
public GamerMappingProfile()
{
CreateMap<Gamer, GamerVM>();
CreateMap<GamerVM, Gamer>();
}
}
然后在创建映射器实例时加载配置文件。
var config = new MapperConfiguration(cfg => {
cfg.AddProfile<GamerMappingProfile>();
cfg.AddProfile<MyOtherProfile>();
});
var mapper = config.CreateMapper();
现在你的模型是干净的——它只包含你的属性并且序列化不需要额外的自定义代码。
自动扫描您的个人资料
http://docs.automapper.org/en/stable/Configuration.html#assembly-scanning-for-auto-configuration
从上面的链接复制
// Scan for all profiles in an assembly
// ... using instance approach:
var config = new MapperConfiguration(cfg => {
cfg.AddProfiles(myAssembly);
});
// ... or static approach:
Mapper.Initialize(cfg => cfg.AddProfiles(myAssembly));
// Can also use assembly names:
Mapper.Initialize(cfg =>
cfg.AddProfiles(new [] {
"Foo.UI",
"Foo.Core"
});
);
// Or marker types for assemblies:
Mapper.Initialize(cfg =>
cfg.AddProfiles(new [] {
typeof(HomeController),
typeof(Entity)
});
);
推荐阅读
- python - pyqt多线程:为什么工作线程阻塞主线程
- godot - 在 Godot GDscript 中返回 null 的函数
- java - 无论输入如何,总是出错
- python - 根据特定列值填充其他行的列值
- drupal - Drupal 8 Command + create_file_url 返回错误的域
- racket - 如何不在 min-30-percent 函数中递归调用辅助函数?
- api - 可视化用户使用 API 进行的一系列交互的工具
- python - Altair:创建组合的整体工具提示
- fabricjs - fabricjs toSVG 在新情况下和从 JSON 加载设计时为带有 clipto 的图像提供不同的输出
- javascript - Vaadin TextArea 将起始行号设置为 1