Reputation: 119
I'm trying to map a navigation property on a one to one relationship but I'm getting null values, here are my entities
public class Client
{
public int ClientId { get; set; }
public string Name { get; set; }
public int BranchId { get; set; }
public Branch Branch{ get; set; }
}
public class Branch
{
public int BranchId { get; set; }
public string Name { get; set; }
}
And this is my Dto
public class ClientDto
{
public int ClientId { get; set; }
public string Name { get; set; }
public string BranchName { get; set; }
}
And these are the mapping configurations I have tried
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<Client, ClientDto>().
ForMember(
dest => dest.BranchName,
opt => opt.MapFrom (src => src.Branch.Name)
);
}
}
and
CreateMap<Client, ClientDto>().IncludeMembers(src => src.Branch);
CreateMap<Branch, ClientDto>().ForMember(
dest => dest.BranchName,
opt => opt.MapFrom(b => b.Name)
);
in both cases I got nulls on BranchName, thank you.
Upvotes: 0
Views: 967
Reputation: 5020
You need to Include
the navigation property on your repository (if using) implementation:
var client = await _context.Clients.Include(c => c.Branch).FirstOrDefaultAsync(c => c.Id == id);
Upvotes: 1
Reputation: 119
Please make sure your actual object (usually from database using ef) includes the desired navigation property by using the Include – S. M. JAHANGIR
This is the correct answer.
Upvotes: 0