Using Automapper in .Net Core, how can I map the nested Foreign key relation?

.net asp.net-core-mvc automapper entity-framework-core

Question

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.

1
0
3/5/2019 1:01:00 AM

Accepted Answer

Check your query command whether it return the expected object Company.

Here is a mini-working demo for query.

var client = _context.Client.Include(c => c.Company).FirstOrDefault(c => c.Id == 1);
Mapper.Initialize(cfg => cfg.CreateMap<Client, ClientDto>());
var result = Mapper.Map<ClientDto>(client);
2
3/5/2019 6:55:40 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow