简体   繁体   中英

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

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"}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM