one to many in entity framework in csharp

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.cs
public class Author
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Book> Books { get; set; }
}
 
public class Book
{
    public int Id { get; set; }
    public string Title { get; set; }
    public virtual Author Author { get; set; }
    public int AuthorId { get; set; }
}
329 chars
15 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.cs
public class LibraryContext : DbContext
{
    public DbSet<Author> Authors { get; set; }
    public DbSet<Book> Books { get; set; }
 
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Author>()
            .HasMany(a => a.Books)
            .WithRequired(b => b.Author)
            .HasForeignKey(b => b.AuthorId);
    }
}
380 chars
14 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.cs
using (var db = new LibraryContext())
{
    var author = new Author { Name = "John Doe" };
    var book1 = new Book { Title = "Book 1", Author = author };
    var book2 = new Book { Title = "Book 2", Author = author };
 
    db.Authors.Add(author);
    db.Books.Add(book1);
    db.Books.Add(book2);
    db.SaveChanges();
}
323 chars
12 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.cs
using (var db = new LibraryContext())
{
    var author = db.Authors.Include(a => a.Books).FirstOrDefault(a => a.Name == "John Doe");
 
    foreach(var book in author.Books)
    {
        Console.WriteLine(book.Title);
    }
}
226 chars
10 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