ASPNETBOILERPLATE - App service method not returning related entities in .NET Core

aspnetboilerplate c# entity-framework-core

Question

I am in the process of converting my .NET MVC5 template into .NET Core MVC template of ASPNETZERO. So all the code I am converting is working just as I need in my MVC5 template solution. My method code is shown below.

  public async Task<EditCompanyDto> GetCompanyForEdit(NullableIdDto input)
    {
        var companyEditDto = (await _companyRepository.GetAsync((int)input.Id));
        var cmp = companyEditDto.MapTo<EditCompanyDto>();
        return cmp;
    }

This code works perfectly in the MVC5 template and returns the related entities of Address, Contact and Note. In the .NET Core solution this exact same code returns only the Address and Contact collections in the above method. It keeps returning the Note collection as NULL.

Shown below is my company entity. I have removed some fields for this post, but have left all the navigational properties.

public class Company : FullAuditedEntity, IMustHaveTenant
{

    public string CompanyTaxId { get; set; }

    public bool ActiveYesNo { get; set; }

    public virtual NoteHeader Note { get; set; }

    public virtual List<CompanyAddress> Addresses { get; set; }

    public virtual List<CompanyContact> Contacts { get; set; }

    public virtual int TenantId { get; set; }

    public Company()
    {
        Addresses = new List<CompanyAddress>();
        Contacts = new List<CompanyContact>();
    }

}
1
2
7/12/2017 2:11:44 AM

Accepted Answer

You say Note collection. As far as i see Note is not collection. Let's assume it's collection. Gabriel's approach is correct. But didn't include Note field. As a result your code should be like this

var company = _companyRepository.GetAll()
                                .Include(c => c.Addresses)
                                .Include(c => c.Contacts)
                                .Include(c => c.Note)
                                .FirstOrDefault(x => x.Id == input.Id);

Note: GetAll() doesn't mean you grab all data from database. GetAll() returns IQueryable. So, you can add Linq methods after it. But if you use GetAllList(), yes it fetches all data from table.

2
7/13/2017 5:50:26 AM

Popular Answer

Try to load your collection by using the Include method.

You can use it like this:

var company = _companyRepository.GetAll()
                                .Include(c => c.Addresses)
                                .Include(c => c.Contacts)
                                .FirstOrDefault(x => x.Id == input.Id);


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