Web Api does not return related data

Asked

Viewed 235 times

0

I’m doing some tests with Web Api (Asp.net core). And with Eager Loading I’m trying to upload a related list, but what I get from Postman is this:

{"id":2,"name":"Computers","sellers":[{"id":1,"name":"Bob Brown","email":"[email protected]","birthDate":"1998-04-21T00:00:00","baseSalary":1000.0

And a warning: Cold not beautify

In my bank I have registered this Department of Id 2 and I have two Selers that are related to this Department, but how can you see what I have return And this Json with only the first related data.


My Entities:

public class Department
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public ICollection<Seller> Sellers { get; set; } = new List<Seller>();
     }

 public class Seller
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public DateTime BirthDate { get; set; }
        public double BaseSalary { get; set; }
        public Department Department { get; set; }
    }

My Service:

 public Department findById(int id)
        {
            return _context.DepartmentItems
            .Include(x => x.Sellers)
            .FirstOrDefault(x => x.Id == id);
        }

My Controller:

    [HttpGet("{id}")]
    public ActionResult<Department> DepartmentItem(int id)
      {
          return _departmentService.findById(id);
      }
  • Márcio, I think your query in LINQ is related to Seller, that is you are consulting Seller and not Departments

  • No, not at all! When I call the api with https:/localhost:5001/api/Department/2, the intention is for json to form with Department after the related items, in this case a seller list. I marked a break point and checked the query, the data see the desired way, but this is not passed to Json

  • the return of _departmentService.findById(id); behind the Sellers populated, but not Json?

1 answer

0

Problem solved! The problem occurred because apparently by default, Json options have a precaution to avoid reference looping.

What I did then was ignore it, as follows:

In my project’s Startup, I inserted:

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

I got the solution Here


But now I have another question: Is it wrong to do so? Since I am globally disabling a "precaution"!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.