0

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

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());
4

2 回答 2

6

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

致电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);
于 2013-02-14T15:39:33.363 回答
0

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

CreateMap<Source, Dest>(MemberList.Source)

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

于 2017-07-20T14:30:16.073 回答