Aida-Hagh / EF-Core

Learn EF Core
1 stars 0 forks source link

Fluent API رابطه یک به چند با #10

Open Aida-Hagh opened 4 months ago

Aida-Hagh commented 4 months ago

هر Author می‌تواند چندین Book داشته باشد.

public class Author {

public int Id { get; set; }
public string Name { get; set; }
public ICollection<Book> Books { get; set; }

}

public class Book {

public int Id { get; set; }
public string Title { get; set; }
public int AuthorId { get; set; }
public Author Author { get; set; }

}

protected override void OnModelCreating(ModelBuilder modelBuilder) {

modelBuilder.Entity<Author>(entity =>
{
    entity.HasKey(e => e.Id);
    entity.Property(e => e.Name).IsRequired();
    entity.HasMany(e => e.Books)
          .WithOne(e => e.Author)
          .HasForeignKey(e => e.AuthorId);
});

modelBuilder.Entity<Book>(entity =>
{
    entity.HasKey(e => e.Id);
    entity.Property(e => e.Title).IsRequired();
    entity.HasOne(e => e.Author)
          .WithMany(e => e.Books)
          .HasForeignKey(e => e.AuthorId);
});

}


عملیات CRUD :

class Program {

static void Main(string[] args)
{
    using (var db = new AppDbContext())
    {
        // ایجاد پایگاه‌داده
        db.Database.EnsureCreated();

        // افزودن داده‌ها
        var author = new Author { Name = "J.K. Rowling" };
        var book1 = new Book { Title = "Harry Potter and the Sorcerer's Stone", Author = author };
        var book2 = new Book { Title = "Harry Potter and the Chamber of Secrets", Author = author };
        db.Authors.Add(author);
        db.Books.AddRange(book1, book2);
        db.SaveChanges();

        // خواندن و نمایش داده‌ها
        var authors = db.Authors
                        .Include(a => a.Books)
                        .ToList();

        foreach (var a in authors)
        {
            Console.WriteLine($"{a.Name} has written:");
            foreach (var b in a.Books)
            {
                Console.WriteLine($" - {b.Title}");
            }
        }
    }
}

}