gpt4 book ai didi

c# - automapper inherting Profile 在 json 中返回额外的属性

转载 作者:行者123 更新时间:2023-11-30 22:58:07 26 4
gpt4 key购买 nike

根据我的阅读,标准是继承 Profile 类,以便 Automapper 检测 map 。 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; }
}

如果我在我的 View 模型上继承了这个类,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)
});
);

关于c# - automapper inherting Profile 在 json 中返回额外的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53213318/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com