Why can't I get all data related to my model?

api asp.net-core-mvc c# entity-framework-core linq

Question

I'm using lazyloading to get all my related data and return json to my API. But I can't seem to get all my related data.

Not sure how to use the include syntax correctly either.

public class Recipe
{
    public int Id { get; set; }
    public string RecipeDescription { get; set; }
    public int? HowManyPersons { get; set; }
    public int? TimeCreated { get; set; }
    public virtual ICollection<IngredientQuantity> IngredientQuantities { get; set;}
    public int RecipeTypeId { get; set; }
    public virtual RecipeType RecipeType { get; set; }
    public string PreparationMethods { get; set; }
}


 public class IngredientQuantity
{
    public int id { get; set; }
    public int IngredientId { get; set; }
    [ForeignKey("IngredientId")]
    public virtual Ingredient Ingredient { get; set; }
    public string Amount { get; set; }
    public int QuantityTypeId { get; set; }
    [ForeignKey("QuantityTypeId")]
    public virtual QuantityType QuantityType { get; set; }
    public int RecipeId { get; set; }
    [ForeignKey("RecipeId")]
    public virtual Recipe Recipe { get; set; }
}

public class Ingredient
{
    public int Id { get; set; }
    public string IngredientDecsription { get; set; }

}

public async Task<IEnumerable<Recipe>> GetAll()
{
    try
    {
        var recipe = await context.Recipe
            .Include(r => r.RecipeType)
            .Include(r => r.IngredientQuantities)
            .ThenInclude(iq => iq.Ingredient)

            .ToListAsync();

        return recipe;
    }
    catch(Exception ex)
    {
        return null;
    }
}

this is my json output:

{"results":[{"ingredientQuantities":[{"ingredient":{"id":1,"ingredientDecsription":"Spinazie"},"quantityType":{"id":1,"quantityTypeDescription":"Handen"}

1
0
8/17/2019 11:56:38 PM

Accepted Answer

You can configure Json.NET to ignore cycles that it finds in the object graph.Try to add below code in startup:

public void ConfigureServices(IServiceCollection services)
{
  ...

  services.AddMvc()
    .AddJsonOptions(
        options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
    );

  ...
}

Refer to Related data and serialization

0
8/19/2019 9:54:30 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow