Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

144
Visualizações
Is there any way I can achieve this in Entity Framework?

I'm running an ASP.NET Core Web API project and I have this model class with a self-referencing association :

public class VehicleCategory 
{
    [Key]
    public int Id { get; set; }
    public string description { get; set; }

    [ForeignKey("ParentVehicleCategoryId")]
    public int? ParentVehicleCategoryId { get; set; }
    [JsonIgnore]
    public virtual VehicleCategory ParentVehicleCategory { get; set; }
    public virtual IEnumerable<VehicleCategory> subVehicleCategories { get; set; }
}

I have configured everything in EF to retrieve get all data and added this config into the startup.cs file to prevent looping:

services.AddControllers().AddNewtonsoftJson(options =>
            options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
        );

The problem is that when I try to get all data from the database, I end up with this json result :

[
  {
    "id": 7,
    "description": "description 1",
    "parentVehicleCategoryId": null,
    "subVehicleCategories": [
      {
        "id": 9,
        "description": "description 2",
        "parentVehicleCategoryId": 7,
        "subVehicleCategories": null
      },
      {
       "id": 10,
        "description": "description 3",
        "parentVehicleCategoryId": 7,
        "subVehicleCategories": null
      }
    ]
  },
  {
    "id": 9,
    "description": "description 2",
    "parentVehicleCategoryId": 7,
    "subVehicleCategories": null
  },
  {
    "id": 10,
    "description": "description 3",
    "parentVehicleCategoryId": 7,
    "subVehicleCategories": null
  }
]

Is there a way I can only have this data with only the array representing the children:

[
  {
    "id": 7,
    "description": "description 1",
    "parentVehicleCategoryId": null,
    "subVehicleCategories": [
      {
        "id": 9,
        "description": "description 2",
        "parentVehicleCategoryId": 7,
        "subVehicleCategories": null
      },
      {
       "id": 10,
        "description": "description 3",
        "parentVehicleCategoryId": 7,
        "subVehicleCategories": null
      }
    ]
  },
 
]

To get data I'm using this code:

var test = _raceContext.VehicleCategories
                       .Include(x => x.subVehicleCategories)
                       .ToList();
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

If you want to include only top-level entities, and their children listed inside, you could use a Where clause to get only those where ParentVehicleCategory is null:

var test = _raceContext.VehicleCategories
                       .Where(vc => vc.ParentVehicleCategory == null)
                       .Include(x => x.subVehicleCategories)
                       .ToList();

This way, the top-level list is the "parent-less" entities, but the second-level entities will appear in your tree, because those entities are all children of some parent, and is included because of your call to the Include method. If you have only two levels of hierarchy, this method will work for you, but if a "child" entity can also be a "parent", you will need to do some extra work.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda