Reputation: 31
I have a project in asp.net core and in this project, I have two entity. First entity is product
public class Product
{
public int id { get; set;}
public string Name { get; set; }
public virtual Brand Brand { get; set; }
}
My second class is
public class Brand
{
public Brand()
{
Products = new List<Products>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual List<Product> Products { get; set; }
}
and I have an APIController like this
public class APIController : ControllerBase
{
public object GetProducts()
{
return decorDB.Products
.Include(p => p.Brand);
}
}
thing I get is a json like this
[
{
"id":1,
"name":"iPhone",
"brand":
{
"id":1,
"name":"Apple",
"products":[
as you see it's not complete, I think EF breaks it to prevent a loop. I want something like this
[
{
"id":1,
"name":"iPhone",
"brand":
{
"id":1,
"name":"Apple",
"products":[]
}
}
]
I don't have any idea to do what!
Upvotes: 0
Views: 63
Reputation: 17668
Disclaimer: not tested but to long for a comment.
I would suggest to make the following changes:
First try to change your action result signature:
public IEnumerable<Product> GetProducts()
Next: try to explicitly disable the round trip in your startup:
services.AddMvc().AddJsonOptions(options =>
{
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
Upvotes: 2