C#C
C#3y ago
Cosen

✅ EntityFramework: Navigation property makes a nested object call

So i have transports and categories models/tables , both are connected with a relationship , one category can have many transports and vice versa. Here is my code:

Category model:
    public class Categories
    {
        [Key]
        public int category_id { get; set; }
        public string name { get; set; }
        // category can have many transports 
        public ICollection<Transports> Transports { get; set; }
    }

Transport model:
public class Transports
{
    [Key]
    public int transport_id { get; set; }
    public int category_id { get; set; }
    public Categories Category { get; set; }
    public string name { get; set; }
}

The problem is i get this schema in swagger api call:

[
  {
    "transport_id": 0,
    "category_id": 0,
    "categories": {
      "category_id": 0,
      "name": "string",
      "transports": [
        "string"
      ]
    },
    "name": "string"
}
]

My category table tries to call another value called "transports" , which i think is from the navigation property in categories model:

    "categories": {
      "category_id": 0,
      "name": "string",
      "transports": [
        "string"
      ]
    },



The problem fixes itself if i add [JsonIgnore] in my categories model above the navigation line:
       // category can have many transports 
        [JsonIgnore]
        public ICollection<Transports> Transports { get; set; }


but it seems this is a bad practice:

I have tried to dto my Transport model:
    public class TransportsDto
    {
        public int transport_id { get; set }
        public int category_id { get; set; }
        public string name { get; set; }


    }

but this way it does not return the relationships with category table.

I am kinda lost here , what am i doing wrong?
Was this page helpful?