0

Here's my model schema.

This is the dependent entity

public class ArticleFee
{
    public int ID { get; set; }
    public string Description { get; set; }
    public Type Type { get; set; }
    public double? FixedFee { get; set; }
    public int? RangeStart { get; set; }
    public int? RangeEnd { get; set; }
    public double? Percentage { get; set; }

    [StringLengthAttribute(1, MinimumLength = 1)]
    public string ArticleLetter { get; set; }
    public Article Article { get; set; }
}
public class Article
    {
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        [KeyAttribute]
        [StringLengthAttribute(1, MinimumLength = 1)]
        public string Letter { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }

        public ICollection<ArticleFee> ArticleFees { get; set; }
    }

Here's how I show data on my route but the ArticleFees just shows an empty array.

[HttpGetAttribute]
    public IEnumerable<Article> Get()
    {
        return _context.Articles
            .Include(a => a.ArticleFees)
            .ToList();
    }
vnc
  • 11

1 Answers1

2

Your model is good(*) and the Get() method too. Your issue is that an infinite loop is detected during the JSON serialization because Article points to ArticleFee and ArticleFee points to Article.

To solve your problem, you must configure the app in Startup.cs so that it "ignore" instead of "throw exception" when such a loop is detected. The solution in .NET Core from this SO answer:

services.AddMvc().AddJsonOptions(options => {
     options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
}); ;

You will need to add using Newtonsoft.Json; to the file.

(*) Assuming that your Type entity is fine.

Community
  • 1
  • 1
Guillaume S.
  • 1,515
  • 1
  • 8
  • 21
  • This may become an issue, but if so, it will throw an exception and not silently serialize an empty array. Also, when reference loops are ignored, the array should be serialized but not the back references inside its elements. – Gert Arnold Feb 26 '17 at 21:24