A principal entity is the entity whose existence supports a dependent entity. A Book can exist without a Rating, whereas a Rating cannot exist without a Book. section 5.2.3
In an EF Core relationship:
- The principal exposes a reference or collection navigation property, such as Book.Rating or Book.Ratings. section 5.2.3
- The dependent stores the foreign key, such as Rating.BookId, which conventionally matches Book.Id. section 5.2.3
- A principal-to-dependent relationship may be one-to-one or one-to-many; many-to-many relationships use collections on both entities. section 5.2.3
Listing 5.8 One-to-one relationship with Book as the parent and Rating as the child
class Book {
public int Id {get;set;}
public Rating? Rating {get;}
}
class Rating
{
public int Id {get;set;}
public int BookId {get;set;}
public Book Book {get;set}
}
This focused C# model shows Book as the principal and Rating as the dependent, including the foreign key and navigation properties. section 5.2.3
Persisting related entities
Create a Book, add Ratings through its collection, save the Book, and query the relationship through EF Core. Use Include when loading Books together with their Ratings. section 5.2.3
