Self referencing loop detected for property in WebApi 2

Viewed 15970

I've created a Web Api to save new products and reviews in database. Below is the WebApi code:

POST api/Products

[ResponseType(typeof(Product))]
public IHttpActionResult PostProduct(Product product)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    db.Products.Add(product);
    db.SaveChanges();

    return CreatedAtRoute("DefaultApi", new { id = product.ProductId }, product);
}

Product class

public class Product
{
    public int ProductId { get; set; }
    [Required]
    public string Name { get; set; }
    public string Category { get; set; }
    public int Price { get; set; }
    //Navigation Property
    public ICollection<Review> Reviews { get; set; }
}

Review class

public class Review
{
    public int ReviewId { get; set; }
    public int ProductId { get; set; }
    [Required]
    public string Title { get; set; }
    public string Description { get; set; }
    //Navigation Property
    public Product Product { get; set; }
}

entity diagram

I'm using google chrome extension 'POSTMAN' to test the api. When I try to save details by creating a POST request in POSTMAN:

{
    "Name": "Product 4",
        "Category": "Category 4",
        "Price": 200,
        "Reviews": [
            {
                "ReviewId": 1,
                "ProductId": 1,
                "Title": "Review 1",
                "Description": "Test review 1",
                "Product": null
            },
            {
                "ReviewId": 2,
                "ProductId": 1,
                "Title": "Review 2",
                "Description": "Test review 2",
                "Product": null
            }
        ]
}

Which shows following error:

"Message":"An error has occurred.",
"ExceptionMessage":"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.",
"ExceptionType":"System.InvalidOperationException",
"StackTrace":null,
"InnerException":{
    "Message":"An error has occurred.",
    "ExceptionMessage":"Self referencing loop detected for property 'Product' with type 'HelloWebAPI.Models.Product'.

How can I resolve this error?

2 Answers
Related