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.
To Model the Fact that a Book can have 0 or 1
BookDetailyou have to make theFKonBook, pointing toBookDetail,nullable, check this:Fluent API Key Relation
and this
}
Is it coherent with reality that a
BookDetailcannot exist without the book itself, so in this case theFKfromBookDetailtoBookmust not benullable. I would not "warp" the name of the FK so I can leverage EFCore conventions:This would be enough for EFCore conventions to figure out that you have a one to one relation and that
Bookis the Independent memeber of the relation andBookDetailis 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