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!