Multiple (optional) one to one Relationships with single navigation property

259 views Asked by At

I'm trying to configure a relationship between two entities where the parent can have multiple (named) childs from the same type while the child should only have one generic parent. Based on the Blog/Posts example I'm trying to configure the following. Blogposts aren't a good example but in my application I have 5 fixed child entities.

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }

    public int? FirstPostId { get; set; }
    public Post FirstPost { get; set; }

    public int? SecondPostId { get; set; }
    public Post SecondPost { 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; }
}

I tried to configure this like:

modelBuilder
    .Entity<Blog>()
    .HasOne(_ => _.FirstPost)
    .WithOne()
    .HasForeignKey<Blog>(_ => _.FirstPostId);
modelBuilder
    .Entity<Blog>()
    .HasOne(_ => _.SecondPost)
    .WithOne()
    .HasForeignKey<Blog>(_ => _.SecondPostId);
modelBuilder
    .Entity<Post>()
    .HasOne(_ => _.Blog)
    .WithOne()
    .HasForeignKey<Post>(_ => _.BlogId);

In my real world problem a Post additionally does not need to belong to a Blog and all foreign keys are composite keys but that should be no problem.

Configured like that FirstPost and SecondPost are recognized but Post.Blog/Post.BlogId is always null.

Any ideas how to solve this?

0

There are 0 answers