该数据库包含表 Machines、Wheels、Characteristics 和 Pilot。汽车的 1 条记录包括 1 条关于 Pilot 的记录、4 条关于车轮和几个特性的记录。在我的模型类中,它看起来像这样:
public class Machines
{
public int Id { get; set; }
public string Description { get; set; }
public string Color { get; set; }
public int Weight { get; set; }
public int Param { get; set; }
public List<Characteristics> characteristics { get; set; }
public List<Wheels> wheels { get; set; }
public Pilot pilot { get; set; }
}
public class Characteristics
{
public int Id { get; set; }
public string Parameter { get; set; }
public string Value { get; set; }
public string Description { get; set; }
public int MachineId { get; set; }
[ForeignKey("MachineId")]
public Machines machine{ get; set; }
}
public class Wheels
{
public int Id { get; set; }
public int Radius { get; set; }
public int Weight { get; set; }
public int MachineId { get; set; }
[ForeignKey("MachineId")]
public Machines machine{ get; set; }
}
public class Pilot
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int MachineId { get; set; }
[ForeignKey("MachineId")]
public Machines machine{ get; set; }
}
当我尝试下载有关机器的完整信息时,如下所示:
var car = context.Machines.Where(x => x.Id == 2)
.Include(m=> m.Wheels)
.Include(m=>m.Charateristics)
.Include(m=>m.Pilot)
.FirstOrDefault();
作为回应,我得到了一辆包含一名飞行员、一系列所有特征和一系列车轮的汽车。但与此同时,车轮数组再次包含有关汽车的信息,其中包括有关车轮的信息(但第二次没有汽车)。
它看起来像这样:
{
"id": 2,
"Description": "",
"Color": "red",
"Weight": 2000,
"Pilot": {
"id": 1,
"Name": "John",
"Description": ""
},
"Wheels": [
{
"id": 7,
"Radius": 14,
"Weight": 5,
"MachineId": 2,
"machine": {
"id": 2,
"Description": "",
"Color": "red",
"Weight": 2000,
"Pilot": {
"id": 1,
"Name": "John",
"Description": ""
},
"Wheels": [
{
"id": 7,
"Radius": 14,
"Weight": 5,
"MachineId": 2
},
...
如何在没有递归数据的情况下获取信息?
此外,该请求需要很长的时间(比 4 个单独的请求长得多)。这微软网站 https://learn.microsoft.com/en-us/ef/ef6/querying/related-data#turn-off-lazy-loading-for-all-entities说如果删除 virtual 关键字,您可以禁用下载。我清理过,但没有帮助。同样在上下文中,我规定this.ChangeTracker.LazyLoadingEnabled = false;
但这也没有帮助。
我还看到很多提到使用 .Load() 函数可以加快请求的执行速度,但我不太明白如何在我的情况下使用它。
UPDATE
由于每个人都建议我包含 Newtonsoft.Json.ReferenceLoopHandling.Ignore,我将提供我的启动文件和上下文文件。事实上,我已经启用了此功能。在添加此内容之前,我根本无法发送响应,添加后,它开始按照我的指示发送(请参阅上面的 JSON 响应)。
我的背景:
public DbSet<Machines> machines{ get; set; }
public DbSet<Characteristics> characteristics{ get; set; }
public DbSet<Wheels> wheels{ get; set; }
public DbSet<Pilot> pilot{ get; set; }
public dbContext(DbContextOptions<dbContext> options) : base(options)
{
this.ChangeTracker.LazyLoadingEnabled = false;
}
我的创业:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddDbContext<dbContext>(options => {
options.UseMySql(Configuration.GetConnectionString("DefaultConnection"),
builder =>
{
builder.EnableRetryOnFailure(5, TimeSpan.FromSeconds(10), null);
});
});
services.AddControllers().AddNewtonsoftJson(x =>
x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
}