AutoMapper exception

本文关键字:exception AutoMapper | 更新日期: 2023-09-27 17:59:38

当我运行代码行Mapper.Map(Account,User)时;我得到一个"缺少类型映射配置或不支持的映射"异常。我还想指出的是,行Mapper.Map(帐户);不会引发异常并返回预期结果。我想做的是将值从Account移动到User,而不创建User的新实例。任何帮助都会很棒。谢谢

public class AccountUpdate
{
    [Email]
    [Required]
    public string Email { get; set; }
    [Required]
    [StringLength(25, MinimumLength = 3, ErrorMessage = "Your name must be between 3 and 25 characters")]
    public string Name { get; set; }
    public string Roles { get; set; }
}
public class User
{
    public User()
    {
        Roles = new List<Role>();
    }
    public int UserId { get; set; }
    public string Email { get; set; }
    public string Name { get; set; }
    public byte[] Password { get; set; }
    public byte[] Salt { get; set; }
    public DateTime CreatedOn { get; set; }
    public DateTime LastLogin { get; set; }
    public virtual ICollection<Role> Roles { get; set; }
}

Mapper.CreateMap<AccountUpdate, User>().ForMember(d => d.Roles, s => s.Ignore());

AutoMapper exception

您没有映射目标类的所有成员。

有关问题的详细信息,请致电Mapper.AssertConfigurationIsValid();

Unmapped members were found. Review the types and members below.
Add a custom mapping expression, ignore, add a custom resolver, or modify the source/destination type
==============================================================
AccountUpdate -> User (Destination member list)
ConsoleApplication1.AccountUpdate -> ConsoleApplication1.User (Destination member list)
--------------------------------------------------------------
UserId
Password
Salt
CreatedOn
LastLogin

若要解决此问题,请显式忽略未映射的成员。


我刚刚测试了这个:

Mapper.CreateMap<AccountUpdate, User>()
        .ForMember(d => d.Roles, s => s.Ignore())
        .ForMember(d => d.UserId, s => s.Ignore())
        .ForMember(d => d.Password, s => s.Ignore())
        .ForMember(d => d.Salt, s => s.Ignore())
        .ForMember(d => d.CreatedOn, s => s.Ignore())
        .ForMember(d => d.LastLogin, s => s.Ignore());
Mapper.AssertConfigurationIsValid();
var update = new AccountUpdate
{
    Email = "foo@bar.com",
    Name = "The name",
    Roles = "not important"
};
var user = Mapper.Map<AccountUpdate, User>(update);
Trace.Assert(user.Email == update.Email);
Trace.Assert(user.Name == update.Name);

这也起作用:

var user = new User();
Mapper.Map(update, user);
Trace.Assert(user.Email == update.Email);
Trace.Assert(user.Name == update.Name);

项目中记录了一个问题,该问题概述了一个潜在的解决方案,即使用源对象作为映射,而不是目标。原始线程在这里,相关的代码示例是:

CreateMap<Source, Dest>(MemberList.Source)

还有一种更通用的扩展方法,有人在链接的问题中写道,这也可能有助于节省时间。