Как сформировать JSON?

public class Department
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Salary { get; set; }
        public IEnumerable<Employee> Employees { get; set; }
    }

[HttpGet("{id}")]
        public async Task<ActionResult<IEnumerable<Department>>> Get(int id)
        {
            var employees = db.Employees.Include(d => d.Department).Where(x => x.Department.Id == id);
            var json = new Department
            {
                Id = id,
                Name = db.Departments.FirstOrDefault(x => x.Id == id).Name,
                Salary = (int)employees.Average(x => x.Salary),
                Employees = employees
        };
            return new ObjectResult(json);
        }

В переменную Employees пытаюсь вставить список, но при обращении вылезает ошибка
JsonException: A possible object cycle was detected which is not supported. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32.

Подскажите пожалуйста что не так?
  • Вопрос задан
  • 83 просмотра
Пригласить эксперта
Ответы на вопрос 1
@Prorom-exe
.NET developer
Скорее всего в твоем списке не сами объекты, а ссылки на них в бд. Нужно Select достать все, что нужно. Есть еще вариант использовать NewtonSoft.Json
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы