Загрузка данных


using DiscountApi.Models;

namespace DiscountApi.Data;

public static class DbInitializer
{
    public static void Initialize(AppDbContext context)
    {
        // 1. Создаём БД и таблицы (если их нет)
        context.Database.EnsureCreated();

        // 2. Если данные уже есть — выходим
        if (context.Brands.Any()) return;

        // 3. Бренды
        var brands = new List<Brand>
        {
            new() { Name = "Nike", Description = "Спортивная одежда" },
            new() { Name = "Adidas", Description = "Спортивные товары" },
            new() { Name = "Zara", Description = "Модная одежда" }
        };
        context.Brands.AddRange(brands);
        context.SaveChanges(); // фиксируем, чтобы получить Id

        // 4. Купоны
        var coupons = new List<Coupon>
        {
            new() { Code = "NIKE20", DiscountPercent = 20, BrandId = brands[0].Id,
                    StartDate = DateTime.UtcNow.AddDays(-10),
                    EndDate = DateTime.UtcNow.AddDays(20) },
            new() { Code = "ADIDAS15", DiscountPercent = 15, BrandId = brands[1].Id,
                    StartDate = DateTime.UtcNow.AddDays(-5),
                    EndDate = DateTime.UtcNow.AddDays(15) }
        };
        context.Coupons.AddRange(coupons);
        context.SaveChanges();
    }
}