In Entity Framework, a one-to-many relationship can be implemented by creating a navigation property in the parent entity that references a collection of child entities. The child entity should also have a reference back to the parent entity.
Here's an example of how to implement a one-to-many relationship between Author
and Book
entities using Entity Framework in C#:
main.cs329 chars15 lines
In the Author
entity, we have defined a collection of Books
as a navigation property using the virtual ICollection<Book>
object. In the Book
entity, we have defined a foreign key AuthorId
and a navigation property Author
to reference the parent Author
entity.
To configure this relationship in the DbContext class, we can use the Fluent API as follows:
main.cs380 chars14 lines
Here, we have overridden the OnModelCreating
method to configure the Author
and Book
entities. We have defined a one-to-many relationship between the Author
and Book
entities using the HasMany
, WithRequired
, and HasForeignKey
methods.
Now, we can use Entity Framework to create the database and insert some data:
main.cs323 chars12 lines
In this example, we have created an Author
object and two Book
objects, each of which references the Author
object. We have added these objects to the context and saved the changes to the database.
Now, we can get the Author
object and its related Books
using Entity Framework:
main.cs226 chars10 lines
In this example, we have used the Include
method to eagerly load the Books
collection for the Author
object. We have then printed the titles of the related Books
to the console.
gistlibby LogSnag