我的数据库是代码优先,我陷入了一个阻碍我继续开发的概念。
我在三个模型中具有 N 对 N 关系:
builder.HasKey(bA => new { at.TicTacToeTruthId, at.TicTacToeActionId });
builder.HasOne<TicTacToeTruth>(b => b.TicTacToeTruth )
.WithMany(b => b.TicTacToeActionTruths)
.HasForeignKey(b => b.TicTacToeTruthId);
builder.HasOne<TicTacToeAction>(a => a.TicTacToeAction)
.WithMany(a => a.TicTacToeActionTruths )
.HasForeignKey(a => a.TicTacToeActionId);
我从控制器获取端点的代码如下:
var TruthsWithActions = await _context.TicTacToeTruths
.Include(bp => bp.TicTacToeActionTruths)
.ThenInclude(bpa => bpa.TicTacToeAction)
.ToListAsync();
当我运行代码时,它会无限循环。通过限制结果,我确信它正在循环中构建我的 json 树。
您知道如何正确加载结果吗?预先感谢您的帮助!!
在 SQL 中它看起来像这样
SELECT *
FROM [dbo].[TicTacToeActionTruths] tr
INNER JOIN [dbo].[TicTacToeActions] act ON act.Id = tr.TicTacToeActionId
INNER JOIN [dbo].[TicTacToeTruths] truth on truth.Id = tr.TicTacToeBodyPartId
我希望能够加载数据,并理解为什么我会遇到这个问题。
我尝试忽略
ReferenceLoopHandling
,以便将循环值从序列化中排除,而不是抛出异常。
builder.Services.AddControllers().AddNewtonsoftJson(options =>
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
);
使用
.Take(3)
限制结果的深度
如果您尝试建立简单的一对一连接,则仅将关系指向一侧就足够了。
builder.Entity<TicTacToeTruth>()
.HasOne<TicTacToeAction>(x => x.TicTacToeAction)
.WithOne(x => x.TicTacToeTruth)
.HasForeignKey<ClientInfo>(x => x.TicTacToeTruthId);
您也不需要映射表,除非您想在其中存储额外的信息
public class TicTacToeTruth
{
public int Id { get; set; }
....
public int TicTacToeActionId { get; set; }
public TicTacToeAction TicTacToeAction { get; set; }
}
public class TicTacToeAction
{
public int Id { get; set; }
....
public int TicTacToeTruthId { get; set; }
public TicTacToeTruth TicTacToeTruth { get; set; }
}
查询
var truths = await context.TicTacToeTruths.Inqlude(x => x.TicTacToeAction).ToListAsync();