using System.Collections.Immutable; using Microsoft.EntityFrameworkCore; namespace DeliveryWebApi.Model; public class DeliveryDbContext(DbContextOptions options) : DbContext(options) { public DbSet Districts { get; init; } public DbSet Orders { get; init; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity() .HasMany(d => d.Orders) .WithOne(o => o.District) .HasForeignKey(o => o.DistrictId) .IsRequired(); modelBuilder.Entity() .HasIndex(d => d.Name) .IsUnique(); // random districts var districtNames = new List { "Viborgskiy", "Primorskiy", "Kalininskiy", "Petrogradskiy", "Center", "Admiralteyskiy", "Vasileostrovskiy", "Kirovskiy", "Krasnoselskiy", "Moskovskiy", "Frunzenskiy", "Nevskiy", "Krasnogvardeyskiy", "Kolpinskiy", "Pushkinskiy", "Pavlovskiy", "Petrodvortsoviy", "Lomonosovskiy", "Kurortniy", "Kronshtadskiy" }; modelBuilder.Entity() .HasData(districtNames.Select((n, i) => new District { Id = i + 1, Name = n })); // random orders var rnd = new Random(); var startDate = new DateTime(2020, 1, 1); var range = (DateTime.Today - startDate).Days; modelBuilder.Entity() .HasData(Enumerable.Range(1, 100).Select(i => { var districtId = rnd.Next(0, districtNames.Count) + 1; var weight = rnd.NextSingle() * 10 + 0.1f; var date = startDate.AddDays(rnd.Next(range)); return new Order { Id = i, DistrictId = districtId, Weight = weight, DeliveryDate = date }; })); } }