Home > front end >  Include produces null in use case with DTO class
Include produces null in use case with DTO class

Time:12-27

I have a linq statement that seems to be working fine and getting correct data:

    [HttpGet]
    public async Task<IActionResult> Get()
    {
      List<DiaryRecord> diaryRecords = await this.Context.DiaryRecords
                                                 .Include(d => d.Project)                                                              
                                                 .Include(e => e.Employees)                                                                  
                                                 .ToListAsync();
      return Ok(diaryRecords);
    }

Employees is

public virtual ICollection<Personell> Employees { get; set; }

I am requesting this list in Client assembly by:

this.DiaryRecords = await this.HttpClient
    .GetFromJsonAsync<IEnumerable<DiaryRecordModelDTO>>("api/Diary");

Where employees is:

public ICollection<PersonellDTO> Employees { get; set; }

As an output this.DiaryRecords has all the needed information, except that Employees is null here. Is an error coming because of different classes PersonellDTO and Personell. How to make it work?

CodePudding user response:

.GetFromJsonAsync is always very tricky and never use interface to deserialize json. And json does not know what classe were used PersonellDTO or Personell to create http response.

in your DTO interface this should be fixed to a concrete class

public List<PersonellDTO> Employees { get; set; }

And I always use code like this for httpclient

    var response = await client.GetAsync(api);

    if (response.IsSuccessStatusCode)
    {
        var stringData = await response.Content.ReadAsStringAsync();
        var result = JsonConvert.DeserializeObject<List<DiaryRecordModelDTO>(stringData);
    }
  • Related