当我运行代码行Mapper.Map(Account,User);我收到“缺少类型映射配置或不支持的映射”异常。我还要注意Mapper.Map(Account)行;不抛出异常并返回预期结果。我想要做的是将值从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());
答案 0 :(得分: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);
答案 1 :(得分:0)
项目中记录的问题概述了一个潜在的解决方案,即使用源对象作为映射,而不是目标。 original thread is here以及相关的代码示例为:
debug.apk
在链接问题中还有一个更通用的扩展方法,也可能有助于节省时间。