In my SQL Server database, I have a table Menus with the following columns:
MenuId int
Name varchar (50)
FkMenuId int
Where is a menu table with recursion
I created a Web API .NET Core 5 project, and generated the Scaffold-DbContext and API Controllers with EF.
I modify the startup.cs in configureservices with:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(opt => opt.AddDefaultPolicy(builder => builder.WithOrigins("*").AllowAnyMethod().AllowAnyHeader()));
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddControllers().AddJsonOptions(options => options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve);
}
Model public partial class Menu { public Menu() { InverseFkMenu = new HashSet(); }
[Key]
public short MenuId { get; set; }
[Required]
[StringLength(50)]
public string Nombre { get; set; }
[Required]
[StringLength(100)]
public string Descripcion { get; set; }
[Required]
[StringLength(50)]
public string Icon { get; set; }
[Required]
[Column("href")]
[StringLength(50)]
public string Href { get; set; }
public bool IsActivo { get; set; }
public short? FkMenuId { get; set; }
[ForeignKey(nameof(FkMenuId))]
[InverseProperty(nameof(Menu.InverseFkMenu))]
public virtual Menu FkMenu { get; set; }
[InverseProperty(nameof(Menu.FkMenu))]
public virtual ICollection<Menu> InverseFkMenu { get; set; }
}
API [HttpGet] return await _context.Menu.ToListAsync();
When executing the project it generates a json in my endpoint that starts with
{ "$id": "1",
"$values": [
{
"$id": "2",
"menuId": 1,
"nombre": "Archivo 1",
"descripcion": "Archivo",
"icon": "Archivo",
"href": "/archivo",
"isActivo": true,
"fkMenuId": null,
"fkMenu": null,
"inverseFkMenu": {
"$id": "3",
"$values": [
From the angular project how to go through it with *NgFor or how to remove $id, $values and $ref.
I appreciate your help, thank you.