C# Entity Framework returning broken JSon when using Include in DbSet

c# entity-framework-core json

Question

I'm trying to make a simple one-to-many relationship in C# using Entity Framework Core, the problem resembles a circular reference problem but no exception is being thrown.

My model classes are:

[Table("Restaurantes")]
public class Restaurante
{
    public int Id { get; set; }
    public string Descricao { get; set; }
    public List<Prato> Pratos { get; set; }
}

[Table("Pratos")]
public class Prato
{
    public int Id { get; set; }
    public string Descricao { get; set; }
    public decimal Preco { get; set; }

    [ForeignKey("RestauranteForeignKey")]
    public Restaurante Restaurante { get; set; }

}
// One Prato (Dish) belongs to One Restaurant and one Restaurant can have many Dishes (Pratos)

I'm returning the Pratos from DB and I want that it returns also with their respective Restaurant:

context.Pratos.Include(r => r.Restaurante).ToList();

The context definition:

public class Contexto : DbContext
{
    public DbSet<Restaurante> Restaurantes { get; set; }
    public DbSet<Prato> Pratos { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Prato>()
            .HasOne(p => p.Restaurante)
            .WithMany(r => r.Pratos)
            .OnDelete(DeleteBehavior.Cascade);
    }
}

But on the browser, the JSON returned is something like:

[ {"id":1,"descricao":"prato 1","preco":1.50,"restaurante":{"id":1,"descricao":"fulano","pratos":[

It returns no more than that. I also tried the documentation but didn't helped in terms of this problem. Thanks in advance.

1
2
2/5/2018 5:34:01 AM

Accepted Answer

If you are using Json.net you probably need to change the DefaultSettings to handle the serialization

JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
    PreserveReferencesHandling = PreserveReferencesHandling.All,
    ReferenceLoopHandling = ReferenceLoopHandling.Serialize
};

Or depending on your particular requirements

PreserveReferencesHandling

  • None : Do not preserve references when serializing types.
  • Objects : Preserve references when serializing into a JSON object structure.
  • Arrays : Preserve references when serializing into a JSON array structure.
  • All : Preserve references when serializing.

ReferenceLoopHandling

  • Error : Throw a JsonSerializationException when a loop is encountered.
  • Ignore : Ignore loop references and do not serialize.
  • Serialize :Serialize loop references.
4
2/5/2018 1:31:49 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow