Let's start with a textbook example for Blogs and Posts using code-first EntityFramework Core:
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public ICollection<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public Blog Blog { get; set; }
}
The EF Core configurures the one-to-many relationship automatically by convension, or it can be done manually using fluent API:
internal class MyContext : DbContext
{
// ...
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Post>()
.HasOne(p => p.Blog)
.WithMany(b => b.Posts);
.HasForeignKey(p => p.BlogId);
}
}
Fine. Now I would like to add an optional FeaturedPost
to a Blog
.
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public ICollection<Post> Posts { get; set; }
public Post FeaturedPost { get; set; }
}
What would be the recommended way of configuring such additional relationship (preserving the original one-to-many relationship) in EF Core? Automatic confuguration results in exception and I fail to figure out how to achieve this manually.