DEV Community

Alex
Alex

Posted on

.NET Learning Notes: EFCore circular reference issue

Let's consider following situation:

public class Category { List<TaskItem> tasks = new List<TaskItem>(); } public class TaskItem { public Category category; } 
Enter fullscreen mode Exit fullscreen mode

**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(); 
Enter fullscreen mode Exit fullscreen mode

2.Use [JsonIgnore]

[JsonIgnore] public Category Category { get; set; } 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)