M
M
mletov2018-06-04 11:47:29
C++ / C#
mletov, 2018-06-04 11:47:29

How to set maximum level for navigational properties when using include?

Please prompt:
There is an entity question

public class Question
    {
        [Key]
        public int Id { get; set; }
        public string Info { get; set; }  
        public ICollection<Answer> Answers { get; set; }
    }

Is the essence of the answer
public class Answer
    {
        [Key]
        public int Id { get; set; }
        public int QuestionId { get; set; }
        [ForeignKey("QuestionId")]
        public Question Question { get; set; }
        public string Info { get; set; }
    }

They refer to each other. And now I want to, say, get all the questions with the answers to them and return
db.Questions.Include(x => x.Answers).ToList()
T to json to they are cyclically tied to each other, then, of course, there is an endless loop.
How to correctly specify the maximum level to which the extraction will be, or how to work with navigation properties in general?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
mletov, 2018-06-04
@mletov

Googled the exact answer
https://github.com/aspnet/Mvc/issues/5910
in Startup.cs

services.AddMvc().AddJsonOptions(x => x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);

E
eRKa, 2018-06-04
@kttotto

If you are trying to serialize an ef object to json, then JsonConvert will then recurse through all the fields inside and of course loop at some point. For such cases, they usually map the ef object to their model and already serialize it.
There is another option here

return JsonConvert.SerializeObject(results, Formatting.Indented, 
new JsonSerializerSettings { 
    ReferenceLoopHandling = ReferenceLoopHandling.Ignore 
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question