据我了解,标准是继承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忽略这些额外的属性?
答案 0 :(得分:2)
您的模型不应继承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)
});
);