在 Entity Framework Core 中添加与同一张表具有多个一对一关系的实体时出现堆栈溢出 [英] Stack overflow when adding an entity with multiple one-to-one relationship with the same table in 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; }
}
在我所拥有的 DbContext
的 OnModelCreating
中:
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!
推荐答案
所以我继续调查这个并发现 这个 答案帮助我解决了这个问题.诀窍是将 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屋!