Foreign key in Webapi with dotnet core

Asked

Viewed 88 times

1

Next I am creating a webapi (I am using the Entity Framework) with two classes, Course and Discipline, where the discipline has the Id of a course, I created 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 right, Course has Id and Name and Discipline has Id, Name and Cursoid, but when I make the GET’s requests the result is as follows:

[
  {
    "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 only need the course id in the discipline.

2 answers

1


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

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

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

It may be necessary to download the package Newtonsoft.Json

For this, in the Package Manager Console execute the command Install-Package Newtonsoft.Json

0

In the Entity Framework Core, you don’t need to create property for 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, don’t forget to include:

_context.Cursos.Include(x=>x.Disciplinas).ToList();
  • I had done it that way, but when I was going to do a POST in the discipline, I couldn’t just pass the Course ID, I had to go through the entire object structure. If I didn’t pass the object Discipline would all NULL

Browser other questions tagged

You are not signed in. Login or sign up in order to post.