Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
¿Hay alguna forma de lograr esto en Entity Framework?

Estoy ejecutando un proyecto ASP.NET Core Web API y tengo esta clase de modelo con una asociación autorreferenciada:

 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; } }

Configuré todo en EF para recuperar todos los datos y agregué esta configuración en el archivo startup.cs para evitar bucles:

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

El problema es que cuando trato de obtener todos los datos de la base de datos, termino con este resultado json:

 [ { "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 } ]

¿Hay alguna manera de que solo pueda tener estos datos con solo la matriz que representa a los niños?

 [ { "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 } ] }, ]

Para obtener datos estoy usando este código:

 var test = _raceContext.VehicleCategories .Include(x => x.subVehicleCategories) .ToList();
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Si desea incluir solo entidades de nivel superior y sus elementos secundarios enumerados dentro, puede usar una cláusula Where para obtener solo aquellas en las que ParentVehicleCategory es null :

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

De esta manera, la lista de nivel superior son las entidades "sin padres", pero las entidades de segundo nivel aparecerán en su árbol, porque esas entidades son todas secundarias de algún padre, y se incluyen debido a su llamada al método Include . Si solo tiene dos niveles de jerarquía, este método funcionará para usted, pero si una entidad "secundaria" también puede ser "principal", deberá realizar un trabajo adicional.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!