当我运行代码行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());
Run Code Online (Sandbox Code Playgroud)
您没有映射目标类的所有成员.
要求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
Run Code Online (Sandbox Code Playgroud)
要解决此问题,请明确忽略未映射的成员.
我刚试过这个:
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);
Run Code Online (Sandbox Code Playgroud)
这也有效:
var user = new User();
Mapper.Map(update, user);
Trace.Assert(user.Email == update.Email);
Trace.Assert(user.Name == update.Name);
Run Code Online (Sandbox Code Playgroud)