In my app one case can have many companies.
My models:
public class Case
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
public string Name { get; set; }
public IList<CaseCompany> CaseCompanies { get; set; }
}
public class CaseInput
{
public Guid Id { get; set; }
[Required]
public string Name { get; set; }
public IList<CaseCompanyInput> CaseCompanyInputs { get; set; }
}
public class Company
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
public string Name { get; set; }
}
public class CompanyInput
{
public Guid Id { get; set; }
[Required]
public string Name { get; set; }
}
public class CaseCompany
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
public Guid CaseId { get; set; }
public Guid CompanyId { get; set; }
public class Case Case { get; set; }
public class Company Company { get; set; }
}
public class CaseCompanyInput
{
public Guid Id { get; set; }
public Guid CaseId { get; set; }
public Guid CompanyId { get; set; }
public class CaseInput CaseInput { get; set; }
public class CompanyInput CompanyInput { get; set; }
}
AutoMapperProfiles.cs:
// In Startup.cs: services.AddAutoMapper(typeof(AutoMapperProfiles));
public class AutoMapperProfiles : Profile
{
public AutoMapperProfiles()
{
CreateMap<Case, CaseInput>().ReverseMap();
CreateMap<CaseCompany, CaseCompanyInput>().ReverseMap();
CreateMap<Company, CompanyInput>().ReverseMap();
}
}
EditCase.cs:
private readonly DBContext _dbContext;
private readonly IMapper _mapper;
[BindProperty]
public CaseInput CaseInput { get; set; }
public EditCase(DBContext dbContext, IMapper mapper)
{
_dbContext = dbContext;
_mapper = mapper;
}
public async Task<IActionResult> OnGetAsync(Guid caseId)
{
var getCase = await _dbContext.Cases.Include(x => x.CaseCompanies).ThenInclude(x => x.Company).FirstOrDefaultAsync(x => x.Id == caseId);
CaseInput = _mapper.Map<CaseInput>(getCase);
Console.WriteLine(getCase.CaseCompanies[0].Company.Name) // gets the company name
Console.WriteLine(CaseInput.CaseCompanyInputs[0].CompanyInput.Name) // CaseInput.Name is not null but CaseCompanyInputs is null
return Page();
}
I've also tried:
CaseInput = await _dbContext.Cases.ProjectTo<CaseInput>(_mapper.ConfigurationProvider).FirstOrDefaultAsync(x => x.Id == caseId);
and
CaseInput = await _dbContext.Cases.Include(x => x.CaseCompanies).ThenInclude(x => x.Company).ProjectTo<CaseInput>(_mapper.ConfigurationProvider).FirstOrDefaultAsync(x => x.Id == caseId);
with the same result: CaseCompanyInputs
is null.
My best guess is that it's an error in the relations of the input models, but I just can't see it. I believe I've followed the naming conventions to make the relations right.
Any help would be appreciated.