Given these entities:
public class StoredArticle
{
public int Id { get; set; }
public string Title { get; set; }
public StoredTimePeriod TimePeriod { get; set; } = null!;
}
public class StoredTimePeriod
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime Start { get; set; }
public DateTime End { get; set; }
}
I want that Article and TimePeriod
have a one-to-one relationship. As I understood TimePeriod
is the principal and Article
is the dependent, because it’s having the foreign key pointing to TimePeriod
This is how I setup their relationship:
modelBuilder.Entity<StoredArticle>(entity =>
{
entity
.HasOne(e => e.TimePeriod)
.WithOne()
.HasForeignKey<StoredArticle>("TimePeriodId")
.OnDelete(DeleteBehavior.Cascade);
});
With this setup, following happens:
- When removing the Article, the TimePeriod remains in the database
- When removing the TimePeriod, the Article is removed too (cascade)
But I want it the other way around. And I don’t wan’t to add ArticleId to TimePeriod, because TimePeriod is used also in other classes.