I know there are some answered questions on SO about 1:0..1-relationships. I have looked at this and this, but don't think they apply to my question.
I have these three (simplified) models in a CMS-system.
public class FrontPageItem
{
public int Id { get; set; }
public int ItemType { get; set; } // 1 = Article, 2 = WebPage, etc...
public int? ArticleId { get; set; }
public Article Article { get; set; }
public int? WebPageId { get; set; }
public WebPage WebPage { get; set; }
}
public class Article
{
public int Id { get; set; }
public string Title { get; set; }
public string Preamble { get; set; }
public string MainText { get; set; }
public int? FrontPageItemId { get; set; }
public FrontPageItem FrontPageItem { get; set; }
}
public class WebPage
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int? FrontPageItemId { get; set; }
public FrontPageItem FrontPageItem { get; set; }
}
The relationships between a FrontPageItem
and each of the different element types are one-to-zero-or-one. An element can exist without being added as a FrontPageItem
, meaning that a FrontPageItem
has a relationship to just one element, either an Article
or a WebPage
.
In an attempt to configure the relationships, I have added this bit of code:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Article>()
.HasOne(p => p.FrontPageItem)
.WithOne(i => i.Article)
.HasForeignKey<FrontPageItem>(b => b.Id);
modelBuilder.Entity<WebPage>()
.HasOne(p => p.FrontPageItem)
.WithOne(i => i.WebPage)
.HasForeignKey<FrontPageItem>(b => b.Id);
}
But I don't think it's correct. I haven't made the CRUD-views for FrontPageItem
yet, but if I try to add items directly in the SQL Server Object Explorer in VS, I have to enter a value for the PK.
What am I doing wrong?