Stack overflow when adding an entity with multiple one-to-one relationship with the same table in Entity Framework Core

蹲街弑〆低调 提交于 2020-04-12 07:27:07

问题


I have an issue when adding entities with multiple one-to-one relationship with the same table in Entity Framework Core. Based on this question I have the following things:

public class Article
{
    public int Id { get; set; }
    public int? PreviousId { get; set; }
    public Article Previous { get; set; }
    public int? NextId { get; set; }
    public Article Next { get; set; }
}

In the OnModelCreating of the DbContext as I have:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.HasDefaultSchema("ab");
    modelBuilder.ApplyConfiguration(new ArticleEntityTypeConfiguration());
}

public class ArticleEntityTypeConfiguration : IEntityTypeConfiguration<Article>
{
    public void Configure(EntityTypeBuilder<Article> builder)
    {
        builder.ToTable("Articles");

        builder.HasKey(table => table.Id);
        builder.Property(table => table.Id).ValueGeneratedOnAdd();

        builder.HasOne(table => table.Previous).WithOne().HasForeignKey<Article>(table => table.PreviousId);
        builder.HasOne(table => table.Next).WithOne().HasForeignKey<Article>(table => table.NextId);
    }
}

And when adding a new article I get a stack overflow error and the app crashes. I add an article with the following code:

public Task AddNewArticleAsync(Article article)
{
    var newArticle = new Article();

    article.Next = newArticle;
    newArticle.Previous = article;

    await _dbContext.Programs.AddAsync(article);
}

Do you know how can I avoid that error? Thanks!


回答1:


if you add a new article,the PreviousId/NextId should be null or an existing Article.Id.If your Artice.Id is increasing, the previousId is the max id of the existing records.

Below is a demo to save new articles:

[HttpPost]
public async Task<IActionResult> Create(Article article)
{
    if (ModelState.IsValid)
    {
        int minArticleId = _context.Articles.Max(a => a.Id);
        var previous = await _context.Articles.Where(s => s.Id == minArticleId).FirstOrDefaultAsync();
        article.PreviousId = minArticleId;
        _context.Add(article);
        await _context.SaveChangesAsync();

        previous.NextId = article.Id;          
        _context.Update(previous);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }

    return View(article);
}



回答2:


So I continue investigating about this and found this answer which helped me to fix the issue. The trick was to change the OnModelCreating of the DbContext to:

public void Configure(EntityTypeBuilder<Article> builder)
{
    builder.ToTable("Articles");

    builder.HasKey(table => table.Id);
    builder.Property(table => table.Id).ValueGeneratedOnAdd();

    builder
        .HasOne(table => table.Previous)
        .WithOne() // <-- one of this must be empty
        .HasForeignKey<Article>(table => table.PreviousId)
        .OnDelete(DeleteBehavior.Restrict);

    builder
        .HasOne(table => table.Next)
        .WithOne(table => table.Previous)
        .HasForeignKey<Article>(table => table.NextId);
}


来源:https://stackoverflow.com/questions/60608252/stack-overflow-when-adding-an-entity-with-multiple-one-to-one-relationship-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!