AutoMapper / AutoMapper.Collection

AutoMapper support for updating existing collections by equivalency
MIT License
245 stars 59 forks source link

mapping foreign key #166

Closed cissemy closed 2 years ago

cissemy commented 2 years ago

I have issue mapping the business class owner's image Url. My classes are : public class Business { public int Id { get; set; } [Required] [ForeignKey("User")] public string UserId { get; set; } public User User { get; set; }
[Required] public string Name { get; set; } = string.Empty; public List BusinessImages { get; set; } } public class User : IdentityUser { [Required] public string Name { get; set; } = string.Empty; public string ImageUrl { get; set; } = string.Empty; public List? Businesses { get; set; }

}
public class BusinessImage
{
    public int Id { get; set; }
    [Required]
    public int BusinessId { get; set; }
    public string ImageUrl { get; set; } = string.Empty;

}

public class BusinessDto { public int Id { get; set; } public string UserId { get; set; } public string UserImageUrl { get; set; } public string Name { get; set; } public List BusinessImages { get; set; } } and the automapper is defined by : public class MapperConfig : Profile {

    public ApplicationDbContext context;
    public MapperConfig(ApplicationDbContext context)
    {
        this.context = context;
    }
    public MapperConfig()
    {
       CreateMap<Business, BusinessDto>()
                  .ForMember(b => b.ImageUrl, d => d.MapFrom(s => s.BusinessImages.FirstOrDefault().ImageUrl))
                  .ForMember(b => b.UserImageUrl, d => d.MapFrom(s => context.Users.Where(u => u.Id == s.UserId).FirstOrDefault().ImageUrl));

} } b.UserImageUrl is alway returning null whereas ImageUrl of the class user has value. Thanks