Home > Enterprise >  Get data from a child table in a parent table in .NET Core Api
Get data from a child table in a parent table in .NET Core Api

Time:09-13

I need some help with a (.NET Core Api) In my (Api) project I have 3 tables Patients - Recommendations - RecoItems

The relesionship of the tables are

  1. Patients > Recommendations = one-to-many
  2. Recommendations > RecoItems = one-to-many

The Api is working fine but in Swagger UI - When I call on GetRecommendationDetailById I get the response as below

{
  "value": {
    "id": "413ab4a1-4b15-4417-afe0-08da94f2718a",
    "comment": "This is my comment",
    "imageFile": null,
    "Image": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA...QmCC",
    "bridge": "38,37,36,35",
    "missing": "32,41",
    "lang": "en",
    "marketID": "2",
    "patientID": "5f7510c8-042c-46a4-3fa2-08da94f2713e",
    "recoItems": []
  },
  "statusCode": 200,
  "contentType": null
}

I don't understand why the recoItems Array is empty in the response when I know that it is not empty in the Database.

How can I fix this ? What do I need to change in my table entities to make this work properly.

public class RecommendationEntity
{
    [Key]
    public Guid Id { get; set; }

    public string? Comment { get; set; }

    public string? Image { get; set; }

    public string? Bridge { get; set; }

    public string? Missing { get; set; }

    public string? Lang { get; set; }

    public string? MarketID { get; set; }

    public Guid PatientID { get; set; }

    public PatientEntity? Patient { get; set; }

    public virtual ICollection<RecoItemEntity>? RecoItems { get; set; }
}

public class RecoItemEntity
{
    [Key]
    public Guid Id { get; set; }

    public string? Title { get; set; }

    public string? Description { get; set; }

    public string? Area { get; set; }

    public Guid RecommendationID { get; set; }

    public RecommendationEntity? Recommendation { get; set; }
}

CodePudding user response:

Interfaces are not working for a serialization. Try this

 public virtual List<RecoItemEntity>? RecoItems { get; set; }

CodePudding user response:

  1. You need to include the RecoItemEntities.

var recs = _db.RecommendationEntities .Include(c => c.RecoItemEntities);

  1. Remove virtual and let it eager loaded.

    public ICollection? RecoItems { get; set; }

  2. If you are using AutoMapper then make sure the properties name matches between source and destination

  • Related