在Entity Framework Core中向同一表添加具有多个一对一关系的实体时,堆栈溢出 [英] Stack overflow when adding an entity with multiple one-to-one relationship with the same table in Entity Framework Core

查看:93
本文介绍了在Entity Framework Core中向同一表添加具有多个一对一关系的实体时,堆栈溢出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Entity Framework Core中向同一表添加具有多个一对一关系的实体时,我遇到问题。基于问题,我有以下事情:

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; }
}

OnModelCreating DbContext >

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!

推荐答案

所以我继续对此进行调查并发现答案有助于我解决此问题。诀窍是将 DbContext OnModelCreating 更改为:

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);
}

这篇关于在Entity Framework Core中向同一表添加具有多个一对一关系的实体时,堆栈溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆