使用延迟加载时,我希望未加载子导航属性 但是我无法避免孩子被加载并在序列化为json时引起循环引用
DbContext
:
public class SampleDbContext : DbContext
{
public SampleDbContext(DbContextOptions<SampleDbContext> options: base(options)
{ }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseLazyLoadingProxies();
}
public DbSet<Parent> Parents { get; set; }
public DbSet<Child> Children { get; set; }
}
模型类:
public class Child
{
public int Id { get; set; }
[ForeignKey("Parent")]
public int ParentId { get; set; }
public string Name { get; set; }
public virtual Parent parent { get; set; }
}
public class Parent
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Child> children { get; set; }
}
启动:
services.AddDbContext<Models.SampleDbContext>(options =>options.UseLazyLoadingProxies().UseSqlite(Configuration.GetConnectionString("DefaultConnection")));
控制器:
[HttpGet]
public async Task<List<Models.Parent>> Get()
{
var sample = _cont.Parents.ToList();
return sample;
}
使用:
答案 0 :(得分:1)
来自ef core docs:
由于EF Core将自动修复导航属性,因此最终可能会在对象图中出现循环。
...
如果使用的是ASP.NET Core,则可以将Json.NET配置为忽略它在对象图中找到的循环。
public void ConfigureServices(IServiceCollection services)
{
...
services.AddMvc()
.AddJsonOptions(
options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
);
...
}