【发布时间】:2019-02-13 20:07:29
【问题描述】:
我正在使用 C#.net 和 ef 核心。我有下面的模型。当我得到我的比赛列表时,我只想得到我的相关用户。但是,我得到了用户和所有用户的比赛。我怎样才能做到这一点?我必须执行以下操作才能显示我的比赛列表:
.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,它使用实体框架使用上述模型调用我的数据库。我的 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 类中创建模型的代码块:
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);
});
}
【问题讨论】:
-
根据您发布的代码,没有明显的理由应该发生这种情况。请在您的问题中添加一个最小、完整、可验证的示例。 stackoverflow.com/help/mcve
标签: asp.net asp.net-core asp.net-core-mvc entity-framework-core