2

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Fnr
  • 2,096
  • 7
  • 41
  • 76
  • It looks like some code somewhere unconditionally swallowed a [circular reference exception](https://stackoverflow.com/q/16949520) while writing to a stream, resulting in incomplete JSON getting written to the stream. – dbc Feb 05 '18 at 01:16

1 Answers1

4

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.
TheGeneral
  • 79,002
  • 9
  • 103
  • 141
  • 1
    Thank you so match. Really, didn't know where to start. While again the solution is so simple, If you know it. – Dinand Feb 27 '20 at 09:32