Last active
June 4, 2026 20:08
-
-
Save sunmeat/a3bee8ffc2120e3eba6a976b2272e113 to your computer and use it in GitHub Desktop.
code first: many-to-many example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| AppDbContext.cs: | |
| using EFCoreCodeFirst.Models; | |
| using Microsoft.EntityFrameworkCore; | |
| using Microsoft.Extensions.Configuration; | |
| namespace EFCoreCodeFirst | |
| { | |
| public class AppDbContext : DbContext | |
| { | |
| public DbSet<User>? Users => Set<User>(); | |
| public DbSet<Order>? Orders => Set<Order>(); | |
| public DbSet<Product>? Products => Set<Product>(); | |
| public DbSet<Category>? Categories => Set<Category>(); | |
| public DbSet<Person>? People { get; set; } | |
| public DbSet<Hobby>? Hobbies { get; set; } | |
| public DbSet<PersonHobby>? PersonHobbies { get; set; } | |
| public AppDbContext() | |
| { | |
| } | |
| protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) | |
| { | |
| if (!optionsBuilder.IsConfigured) | |
| { | |
| var configuration = new ConfigurationBuilder() | |
| .SetBasePath(Directory.GetCurrentDirectory()) | |
| .AddJsonFile("appsettings.json") | |
| .Build(); | |
| optionsBuilder.UseSqlServer(configuration.GetConnectionString("DefaultConnection")); | |
| } | |
| } | |
| protected override void OnModelCreating(ModelBuilder modelBuilder) | |
| { | |
| base.OnModelCreating(modelBuilder); | |
| // налаштування зв'язку М-М | |
| modelBuilder.Entity<PersonHobby>() | |
| .HasKey(ph => new { ph.PersonId, ph.HobbyId }); | |
| modelBuilder.Entity<PersonHobby>() | |
| .HasOne(ph => ph.Person) | |
| .WithMany(p => p.PersonHobbies) | |
| .HasForeignKey(ph => ph.PersonId); | |
| modelBuilder.Entity<PersonHobby>() | |
| .HasOne(ph => ph.Hobby) | |
| .WithMany(h => h.PersonHobbies) | |
| .HasForeignKey(ph => ph.HobbyId); | |
| } | |
| } | |
| } | |
| ============================================================================================= | |
| Person.cs: | |
| namespace EFCoreCodeFirst.Models | |
| { | |
| public class Person | |
| { | |
| public int PersonId { get; set; } // Primary Key | |
| public string? Name { get; set; } | |
| public ICollection<PersonHobby>? PersonHobbies { get; set; } | |
| } | |
| } | |
| ============================================================================================= | |
| Hobby.cs: | |
| namespace EFCoreCodeFirst.Models | |
| { | |
| public class Hobby | |
| { | |
| public int HobbyId { get; set; } // Primary Key | |
| public string? Name { get; set; } | |
| public ICollection<PersonHobby>? PersonHobbies { get; set; } | |
| } | |
| } | |
| ============================================================================================= | |
| PersonHobby.cs: | |
| namespace EFCoreCodeFirst.Models | |
| { | |
| public class PersonHobby | |
| { | |
| public int PersonId { get; set; } // зовнішній ключ до Person | |
| public Person? Person { get; set; } | |
| public int HobbyId { get; set; } // зовнішній ключ до Hobby | |
| public Hobby? Hobby { get; set; } | |
| } | |
| } | |
| ============================================================================================= | |
| Program.cs: | |
| using EFCoreCodeFirst.Models; | |
| using Microsoft.EntityFrameworkCore; | |
| namespace EFCoreCodeFirst | |
| { | |
| class Program | |
| { | |
| static async Task Main() | |
| { | |
| Console.Title = "Міграції"; | |
| Console.OutputEncoding = System.Text.Encoding.UTF8; | |
| await using var db = new AppDbContext(); | |
| // await db.Database.EnsureDeletedAsync(); // видаляє БД, якщо вона існувала | |
| Console.WriteLine("Перевірка та застосування міграцій..."); | |
| await db.Database.MigrateAsync(); | |
| Console.WriteLine("Міграції застосовані (або вже були актуальні).\n"); | |
| var hobby1 = new Hobby { Name = "Футбол" }; | |
| var hobby2 = new Hobby { Name = "Малювання" }; | |
| var hobby3 = new Hobby { Name = "Читання" }; | |
| var hobby4 = new Hobby { Name = "Подорожі" }; | |
| var hobby5 = new Hobby { Name = "Кулінарія" }; | |
| db.Hobbies?.AddRange(hobby1, hobby2, hobby3, hobby4, hobby5); | |
| var person1 = new Person { Name = "Олександр" }; | |
| var person2 = new Person { Name = "Руслан" }; | |
| var person3 = new Person { Name = "Максим" }; | |
| var person4 = new Person { Name = "Карина" }; | |
| var person5 = new Person { Name = "Аліса" }; | |
| db.People?.AddRange(person1, person2, person3, person4, person5); | |
| db.PersonHobbies?.AddRange( | |
| new PersonHobby { Person = person1, Hobby = hobby1 }, | |
| new PersonHobby { Person = person1, Hobby = hobby3 }, | |
| new PersonHobby { Person = person2, Hobby = hobby2 }, | |
| new PersonHobby { Person = person2, Hobby = hobby4 }, | |
| new PersonHobby { Person = person3, Hobby = hobby5 }, | |
| new PersonHobby { Person = person3, Hobby = hobby1 }, | |
| new PersonHobby { Person = person4, Hobby = hobby2 }, | |
| new PersonHobby { Person = person4, Hobby = hobby5 }, | |
| new PersonHobby { Person = person5, Hobby = hobby3 }, | |
| new PersonHobby { Person = person5, Hobby = hobby4 } | |
| ); | |
| db.SaveChanges(); | |
| using (var context = new AppDbContext()) | |
| { | |
| var peopleWithHobbies = context.People?.Include(p => p.PersonHobbies!).ThenInclude(ph => ph.Hobby).ToList(); | |
| foreach (var person in peopleWithHobbies!) | |
| { | |
| Console.WriteLine($"{person.Name}"); | |
| foreach (var personHobby in person.PersonHobbies!) | |
| { | |
| Console.WriteLine($" - Захоплення: {personHobby.Hobby?.Name}"); | |
| } | |
| } | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment