我正在使用惰性加载来获取我所有的相关数据,并将json返回到我的API。但是我似乎无法获取所有相关数据。
也不知道如何正确使用include语法。
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;
}
}
这是我的json输出:
{“ results”:[{“ ingredientQuantities”:[{“ ingredient”:{“ id”:1,“ ingredientDecsription”:“ Spinazie”},“ quantityType”:{“ id”:1,“ quantityTypeDescription” :“处理”}
答案 0 :(得分:0)
您可以将Json.NET配置为忽略它在对象图中找到的循环。尝试在启动时添加以下代码:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddMvc()
.AddJsonOptions(
options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
);
...
}