one to one relationship with ef core 5 (use 2 FK)

1.7k Views Asked by At

I have these 2 Entities. each book can have one or zero BookDetail (1 to 1 Relationship)

 public class Book
 {
        public int BookId{ get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public string ISBN { get; set; }
        public string Price { get; set; }

        public int BookDetailId { get; set; } /* FK for BookDetail */
        public BookDetail BookDetail{ get; set; }
 }

 public class BookDetail
 {
        public int BookDetailId{ get; set; }
        public string Weight { get; set; }
        public string NumberOfPages { get; set; }
        public DateTime PublicationDate { get; set; }

        public int BooklId { get; set; } /* FK for Book */
        public Book Book{ get; set; } 
 }

I want to have 2 sides foreign key, I just find solutions for just one side foreign key but I want to store FK Id of BookDetail on Book and vice versa in EF Core 5.

1

There are 1 best solutions below

0
david-ao On

To Model the Fact that a Book can have 0 or 1 BookDetail you have to make the FK on Book, pointing to BookDetail, nullable, check this:

Fluent API Key Relation

and this

 public class Book
 {
    public int BookId{ get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string ISBN { get; set; }
    public string Price { get; set; }

    public int? BookDetailId { get; set; } /* nullable FK to BookDetail */
    public BookDetail BookDetail{ get; set; }

}

Is it coherent with reality that a BookDetail cannot exist without the book itself, so in this case the FK from BookDetail to Book must not be nullable. I would not "warp" the name of the FK so I can leverage EFCore conventions:

 public class BookDetail
 {
    public int BookDetailId{ get; set; }
    public string Weight { get; set; }
    public string NumberOfPages { get; set; }
    public DateTime PublicationDate { get; set; }

    public int BookId { get; set; } /* FK to Book by conventions*/
    public Book Book{ get; set; }
}

This would be enough for EFCore conventions to figure out that you have a one to one relation and that Book is the Independent memeber of the relation and BookDetail is the dependent one: The Independent is always required.

A little extra info: you might want to check owned entites, your BookDetail entity can be seen as a "complex property" of Book, this would mean though that BookDetail could not have an Id by itself.

Owned Entity Types