我有2个型号:
User.cs:
Authentication.cs
我希望身份验证模型中的电子邮件和密码映射到用户模型中的电子邮件和密码,因此在我的MappingProfile中,我有:
public UserProfile()
{
CreateMap<User, Authentication>()
.ForMember(dest => dest.Email, o => o.MapFrom(src => src.Email))
.ForMember(dest => dest.Password, o => o.MapFrom(src => src.Password))
.IgnoreAllNonExisting();
}
IgnoreAllNonExisting是一个自定义扩展,如下所示:
public static IMappingExpression<TSource, TDestination> IgnoreAllNonExisting<TSource, TDestination>
(this IMappingExpression<TSource, TDestination> expression)
{
var flags = BindingFlags.Public | BindingFlags.Instance;
var sourceType = typeof(TSource);
var destinationProperties = typeof(TDestination).GetProperties(flags);
foreach (var property in destinationProperties)
{
if (sourceType.GetProperty(property.Name, flags) == null)
{
expression.ForMember(property.Name, opt => opt.Ignore());
}
}
return expression;
}
尽管扩展名仍然出现此错误:
未映射的属性:名字;姓氏
几乎就像我的扩展名被忽略了一样?
有人知道我在做什么错吗?
答案 0 :(得分:0)
需要创建从 User 到 Authentication 的映射,反之亦然(两个方向都不是一个映射)。
由于 User 和 Authentication 的属性名称相同,因此AutoMapper会进行自动映射。
不需要扩展方法 IgnoreAllNonExisting ,AutoMapper会为您完成这项工作。
public static void Test01()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<User, Authentication>();
cfg.CreateMap<Authentication, User>();
});
var mapper = config.CreateMapper();
var authentication = mapper.Map<User, Authentication>(new User { Email = "email", Password = "pass", Firstname = "first", Lastname = "last" });
var user = mapper.Map<Authentication, User>(new Authentication { Email = "email", Password = "pass" });
}