Foreign key in WebApi with dotnet core

1

Next I'm creating a webapi (I'm using the Entity Framework) with two classes, Course and Discipline, where the course has the Id of a course, I created it as follows:

public class Curso
{
    public int Id { get; set; }
    public string Nome { get; set; }

    public List<Disciplina> Disciplinas{ get; set; }
}

public class Disciplina
{
    public int Id { get; set; }
    public string Nome { get; set; }

    public int CursoId { get; set; }
    public Curso Curso{ get; set; }
}

The OnModelCreating method looks like this:

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Disciplina>()
            .HasOne(p => p.Curso)
            .WithMany(p => p.Disciplinas)
            .HasForeignKey(p => p.CursoId);
        base.OnModelCreating(modelBuilder);
    }

In the database created certain, Course has Id and Name and Discipline has Id, Name and CourseId, however when I make the GET requests the result is the following:

[
  {
    "id": 1,
    "nome": "SI",
    "disciplinas": 1,
  }
]

[
  {
    "id": 1,
    "nome": "POO",
    "cursoId": 1,
    "curso": null
  }
]

Is there any way for Entity to map better so that those keys that are coming NULL do not appear in JSON?

Remembering that I need only the course ID in the course.

    
asked by anonymous 24.05.2018 / 04:06

2 answers

1
  

Is there any way for Entity to map better so these keys that   are coming NULL does not appear in JSON?

To ignore null objects it is necessary to configure this in Startup.cs , you can do as follows

services.AddMvc()
        .AddJsonOptions(options =>
        {
            options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
        });

It may be necessary to download the package Newtonsoft.Json

To do this, in the Package Manager Console run the Install-Package Newtonsoft.Json     

24.05.2018 / 05:06
0

In Entity Framework Core , you do not need to create the property for the foreign key. Just do:

public class Curso
{
    public int Id { get; set; }
    public string Nome { get; set; }

    public List<Disciplina> Disciplinas{ get; set; }
}

public class Disciplina
{
    public int Id { get; set; }
    public string Nome { get; set; }

    public Curso Curso{ get; set; }
}


protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Disciplina>().HasOne(p => p.Curso);
    modelBuilder.Entity<Curso>().HasMany(p => p.Disciplinas);

    base.OnModelCreating(modelBuilder);
}

When selecting data, do not forget to include:

_context.Cursos.Include(x=>x.Disciplinas).ToList();
    
24.05.2018 / 04:56