46 lines
1.8 KiB
C#
46 lines
1.8 KiB
C#
|
using System.Collections.Immutable;
|
||
|
using Microsoft.EntityFrameworkCore;
|
||
|
|
||
|
namespace DeliveryWebApi.Model;
|
||
|
|
||
|
public class DeliveryDbContext(DbContextOptions<DeliveryDbContext> options) : DbContext(options)
|
||
|
{
|
||
|
public DbSet<District> Districts { get; init; }
|
||
|
public DbSet<Order> Orders { get; init; }
|
||
|
|
||
|
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||
|
{
|
||
|
modelBuilder.Entity<District>()
|
||
|
.HasMany(d => d.Orders)
|
||
|
.WithOne(o => o.District)
|
||
|
.HasForeignKey(o => o.DistrictId)
|
||
|
.IsRequired();
|
||
|
|
||
|
modelBuilder.Entity<District>()
|
||
|
.HasIndex(d => d.Name)
|
||
|
.IsUnique();
|
||
|
|
||
|
// random districts
|
||
|
var districtNames = new List<string>
|
||
|
{
|
||
|
"Viborgskiy", "Primorskiy", "Kalininskiy", "Petrogradskiy", "Center", "Admiralteyskiy", "Vasileostrovskiy",
|
||
|
"Kirovskiy", "Krasnoselskiy", "Moskovskiy", "Frunzenskiy", "Nevskiy", "Krasnogvardeyskiy", "Kolpinskiy",
|
||
|
"Pushkinskiy", "Pavlovskiy", "Petrodvortsoviy", "Lomonosovskiy", "Kurortniy", "Kronshtadskiy"
|
||
|
};
|
||
|
modelBuilder.Entity<District>()
|
||
|
.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<Order>()
|
||
|
.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 };
|
||
|
}));
|
||
|
}
|
||
|
}
|