简体   繁体   中英

AutoMapper - AutoMapper.AutoMapperMappingException

I'm having this exception when I'm trying to map from one object to another.

On my global.asax.cs I got this:

RoleManager<IdentityRole> roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new AppContext()));
        Mapper.Initialize(cfg =>
        {
            cfg.CreateMap<AppUser, TokenAuthorizationModel>()
            .ForMember(dest => dest.UserName, opt => opt.MapFrom(src => src.UserName))
            .ForMember(dest => dest.Role, opt => opt.MapFrom(src => roleManager.FindById(src.Roles.First().RoleId).Name));
        });

And I got this AutoMapper.AutoMapperMappingException exception on my login controller, especifically on this line:

TokenAuthorizationModel tokenClaims = Mapper.Map<TokenAuthorizationModel>(validUser);

And these are my models:

public class AppUser : IdentityUser
{
    public virtual List<CourseModel> Courses { get; set; }
    public string FullName { get; set; }
    public int Reputation { get; set; }
}

And destination:

public class TokenAuthorizationModel
{
    public string UserName { get; set; }
    public string Role { get; set; }
}

Can anybody give me hand? Thanks in advance! :)

I think the problem is at this part:

.ForMember(dest => dest.Role, opt => opt.MapFrom(src => roleManager.FindById(src.Roles.First().RoleId).Name));

I would not use MapFrom in this case. Try to use ResolveUsing method instead which takes a lambda function.

.ForMember(dest => dest.Role, opt => opt.ResolveUsing(src => roleManager.FindById(src.Roles.First().RoleId).Name));

If this does not work please let me know!

您应该为Role属性编写一个解析器,并在其中使用依赖项注入,以便拥有与应用程序其他任何地方一样的正确DbContext。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM