【发布时间】:2022-09-24 12:11:11
【问题描述】:
我知道关于这个但是有很多问题(和答案)没有任何在使用 .net6 和 automapper 11.01.1 时,这些对我有用
他们似乎在最新的自动映射器中删除了许多 Ignore、IgnoreAllUnmapped 和 ForAllOtherMembers。
如果我对ForAllMembers 使用ignore(在ForMember 之前或之后),它将忽略所有字段,即使是我用地图指定的字段。
问题:我有两个具有相同名称字段的类,但我只想映射一些并忽略其余部分。 (请不要说“为什么需要自动映射器”,这不是这里的问题)。
在这种情况下我需要使用 automapper 但不确定他们是否支持这个?我可能错过了一个nuget吗?我只使用“AutoMapper 11.01.1”
public class User1
{
public string Name { get; set; } = \"Foo\";
public int Age { get; set; } = 7;
public string Phone { get; set;} = \"123456789\";
}
public class User2
{
public string FirstLastName { get; set; }
public int Age { get; set; }
public string Phone { get; set; }
}
public class AutoMapperProfile : Profile
{
public AutoMapperProfile()
{
CreateMap<User1, User2>()
.ForMember(dest => dest.FirstLastName, opt => opt.MapFrom(src => src.Name))
//.ForMember(dest => dest.Age, src => src.Ignore()); // works BUT I do not want to ignore every field manually
//.ForAllMembers(dest => dest.Ignore()) // doesn\'t work, clears all fields
//.ValidateMemberList(MemberList.None) // doesn\'t work
;
}
}
void Main()
{
var user1 = new User1();
var config = new MapperConfiguration(mc => mc.AddProfile(new AutoMapperProfile()));
Mapper mapper = new Mapper(config);
var user2 = mapper.Map<User2>(user1);
user2.Dump();
}
-
不幸的是,我不认为 IgnoreAllUnmapped 仍然存在于 automapper 中,除非我错过了一些 nuget 或使用了错误的 nuget。
标签: c# mapping automapper