我正在使用 C#.net 和 ef core。我有以下型号。当我获取竞赛列表时,我只想获取相关用户。但是,我正在获取用户和所有用户的竞赛。我怎样才能实现这个目标?我必须执行以下操作才能显示我的比赛列表:
.AddJsonOptions(opt => opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore)
public partial class Competition
{
public int CompetitionId { get; set; }
public int UserId { get; set; }
public User User { get; set; }
}
public partial class User
{
public int UserId { get; set; }
public string Email { get; set; }
public string UserName { get; set; }
public ICollection<Competition> Competitions { get; set; }
}
我有一个 API,它使用 Entity Framework 使用上述模型来调用我的数据库。我的 api 中导致循环引用的调用如下:
[Produces("application/json")]
[Route("api/Competitions")]
public class CompetitionsController : Controller
{
private readonly ApplicationDBContext _context;
public CompetitionsController(ApplicationDBContext context)
{
_context = context;
}
// GET: api/Competitions
[HttpGet]
public IEnumerable<Competition> GetCompetitions()
{
//return _context.Competitions;
return _context.Competitions
.Include(u => u.User).ToList();
}
}
下面是我的 ApplicationDBContext 类中的 onmodelcreating 代码块:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Competition>(entity =>
{
entity.HasKey(e => e.CompetitionId);
entity.HasOne(d => d.User)
.WithMany(p => p.Competitions)
.HasForeignKey(d => d.UserId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Competitions_Users");
});
modelBuilder.Entity<User>(entity =>
{
entity.HasKey(e => e.UserId);
entity.HasIndex(e => e.UserName)
.HasName("UC_UserName")
.IsUnique();
entity.Property(e => e.Email)
.HasMaxLength(40)
.IsUnicode(false);
entity.Property(e => e.UserName)
.HasMaxLength(40)
.IsUnicode(false);
});
}
最佳答案
老问题,但以防万一有人仍在寻找。 一种解决方案是:
services.AddMvc()
.AddJsonOptions(options => {
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
关于asp.net - EF Core 实体循环引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52240008/