Skip to content

Instantly share code, notes, and snippets.

@sunmeat
Last active June 13, 2026 13:13
Show Gist options
  • Select an option

  • Save sunmeat/8efc14cb3326b754cbada343955a0582 to your computer and use it in GitHub Desktop.

Select an option

Save sunmeat/8efc14cb3326b754cbada343955a0582 to your computer and use it in GitHub Desktop.
CRUD operations entity framework core code first many to many example
... контекст ...
... моделі ...
=========================================================================================================
Repositories / PersonRepository.cs:
public class PersonRepository
{
public void GetAllPeople()
{
using var context = new ApplicationDbContext();
var people = context.People?.Include(p => p.Hobbies).ToList();
foreach (var person in people!)
{
Console.WriteLine($"{person.Name}");
foreach (var hobby in person.Hobbies)
{
Console.WriteLine($" - Хобі: {hobby.Name}");
}
}
}
public void AddPerson(string name, List<string> hobbies)
{
using var context = new ApplicationDbContext();
var person = new Person { Name = name };
foreach (var hobbyName in hobbies)
{
var hobby = context.Hobbies?.FirstOrDefault(h => h.Name == hobbyName) ?? new Hobby { Name = hobbyName };
person.Hobbies.Add(hobby);
}
context.People?.Add(person);
context.SaveChanges();
Console.WriteLine($"Людина {name} додана!");
}
public void UpdatePersonHobbies(string personName, List<string> newHobbies)
{
using var context = new ApplicationDbContext();
var person = context.People?.Include(p => p.Hobbies).FirstOrDefault(p => p.Name == personName);
if (person == null)
{
Console.WriteLine($"Людину з ім'ям {personName} не знайдено.");
return;
}
person.Hobbies.Clear();
foreach (var hobbyName in newHobbies)
{
var hobby = context.Hobbies?.FirstOrDefault(h => h.Name == hobbyName) ?? new Hobby { Name = hobbyName };
person.Hobbies.Add(hobby);
}
context.SaveChanges();
Console.WriteLine($"Хобі {personName} оновлено!");
}
public void DeletePerson(string personName)
{
using var context = new ApplicationDbContext();
var person = context.People?.Include(p => p.Hobbies).FirstOrDefault(p => p.Name == personName);
if (person == null)
{
Console.WriteLine($"Людину з ім'ям {personName} не знайдено.");
return;
}
context.People?.Remove(person);
context.SaveChanges();
Console.WriteLine($"Людину {personName} видалено!");
}
}
=========================================================================================================
Program.cs:
using EFCoreCodeFirst.Repositories;
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();
Console.WriteLine("Перевірка та застосування міграцій...");
await db.Database.MigrateAsync();
Console.WriteLine("Міграції застосовані (або вже були актуальні).\n");
var repo = new PersonRepository();
repo.AddPerson("Олександр", new List<string> { "Футбол", "Читання" });
repo.AddPerson("Артем", new List<string> { "Малювання", "Подорожі" });
repo.GetAllPeople();
repo.UpdatePersonHobbies("Олександр", new List<string> { "Готування", "Подорожі" });
repo.GetAllPeople();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment