using System; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using ThAmCo.Events.Data; namespace ThAmCo.Events.Data { public class EventsDbContext : DbContext { public DbSet Customers { get; set; } public DbSet Events { get; set; } public DbSet Guests { get; set; } public DbSet Staffing { get; set; } public DbSet Staff { get; set; } private IHostingEnvironment HostEnv { get; } public EventsDbContext(DbContextOptions options, IHostingEnvironment env) : base(options) { HostEnv = env; } protected override void OnConfiguring(DbContextOptionsBuilder builder) { base.OnConfiguring(builder); } protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); builder.HasDefaultSchema("thamco.events"); builder.Entity() .HasKey(b => new { b.CustomerId, b.EventId }); builder.Entity() .HasKey(s => new { s.StaffId, s.EventId }); builder.Entity() .HasMany(c => c.Bookings) .WithOne(b => b.Customer) .HasForeignKey(b => b.CustomerId); builder.Entity() .HasMany(e => e.Bookings) .WithOne(b => b.Event) .HasForeignKey(b => b.EventId); builder.Entity() .HasMany(e => e.Staffings) .WithOne(b => b.Event) .HasForeignKey(b => b.EventId); builder.Entity() .Property(e => e.TypeId) .IsFixedLength(); builder.Entity() .HasMany(s => s.Staffings) .WithOne(b => b.Staff) .HasForeignKey(b => b.StaffId); // seed data for debug / development testing if (HostEnv != null && HostEnv.IsDevelopment()) { builder.Entity().HasData( new Customer { Id = 1, Surname = "Robertson", FirstName = "Robert", Email = "bob@example.com" }, new Customer { Id = 2, Surname = "Thornton", FirstName = "Betty", Email = "betty@example.com" }, new Customer { Id = 3, Surname = "Jellybeans", FirstName = "Jin", Email = "jin@example.com" } ); builder.Entity().HasData( new Event { Id = 1, Title = "Bob's Big 50", Date = new DateTime(2016, 4, 12), Duration = new TimeSpan(6, 0, 0), TypeId = "PTY" }, new Event { Id = 2, Title = "Best Wedding Yet", Date = new DateTime(2018, 12, 1), Duration = new TimeSpan(12, 0, 0), TypeId = "WED" } ); builder.Entity().HasData( new GuestBooking { CustomerId = 1, EventId = 1, Attended = true }, new GuestBooking { CustomerId = 2, EventId = 1, Attended = false }, new GuestBooking { CustomerId = 1, EventId = 2, Attended = false }, new GuestBooking { CustomerId = 3, EventId = 2, Attended = false } ); builder.Entity().HasData( new Staff { Id = 1, Surname = "Partridge", FirstName = "Alan", Email = "a@a.a", FirstAid = false }, new Staff { Id = 2, Surname = "Stephenson", FirstName = "Roger", Email = "rege@hotmail.com", FirstAid = true}, new Staff { Id = 3, Surname = "Smith", FirstName = "Alans", Email = "alans@jims.net", FirstAid = false } ); builder.Entity().HasData( new Staffing { StaffId = 1, EventId = 2 }, new Staffing { StaffId = 2, EventId = 1 }, new Staffing { StaffId = 3, EventId = 1 } ); } } } }