Let's consider following situation:
public class Category {
List<TaskItem> tasks = new List<TaskItem>();
}
public class TaskItem {
public Category category;
}
**If we use dbContext.Category.Include(c => c.tasks).....
It will cause circular reference issue, EF Core will load Category then include its tasks. Each TaskItem contains a reference to its Category, then that Category includes its Tasks again.....
This Creates: performances issues, Stack overflow errors, problems when serializing to JSON.
1.Use DTO(Data Transfer Objects)
var categories = context.Categories
.Where(c => !c.IsDeleted)
.Select(c => new {
c.Id,
c.Name,
Tasks = c.Tasks
.Where(t => !t.IsDeleted)
.Select(t => new {
t.Id,
t.Title,
t.IsCompleted
}).ToList()
})
.ToList();
2.Use [JsonIgnore]
[JsonIgnore]
public Category Category { get; set; }
Top comments (0)