I am trying to map the FK relation in my DTO class. However, I always get 'null' values as response in Postman.
Since the project includes companies that can be either clients/ partners etc. I have created a base table of company and created clients with FK relationship to company.
Company Class
public class Company
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[MaxLength(50)]
public string Name { get; set; }
[MaxLength(50)]
public string Street { get; set; }
public int Zip { get; set; }
[MaxLength(50)]
public string City { get; set; }
Client Class
public class Client
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[ForeignKey("CompanyId")]
public Company Company { get; set; }
public int CompanyId { get; set; }
public ICollection<User> Users { get; set; }
= new List<User>();
public ICollection<Department> Departments { get; set; }
= new List<Department>();
ClientDTO
public class ClientDto
{
public int Id { get; set; }
public string CompanyName { get; set; }
public string CompanyStreet { get; set; }
public ICollection<UserDto> Users { get; set; }
= new List<UserDto>();
}
AutoMapper in Startup Class
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Client, ClientDto>();
cfg.CreateMap<Client, ClientWithoutUsersDto>();
cfg.CreateMap<Company, CompanyDto>();
cfg.CreateMap<User, UserDto>();
});
Whatever mapping I try I get the same Json Response in Postmane:
"id": 1,
"companyName": null,
"streetName": null
I am not sure whether Automapper supports nested FK mapping. I know that the User Collection works well.
Mapor withProjectTo? IfMap, are you loading theClient.Companyproperty? It won't be populated by default, you need toIncludeit - see Loading Related Data