using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using System.Collections.Generic; using System.Net; using Weifer.Database.EF.Entitys; namespace Weifer.Database.EF { public class DatabaseContext : DbContext { public DatabaseContext() { } public DatabaseContext(DbContextOptions options) : base(options) { } public virtual DbSet Customers { get; set; } public virtual DbSet ShoppingLists { get; set; } public virtual DbSet ShoppingItems { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .Build(); var connectionString = configuration.GetConnectionString("ShoppingApp"); optionsBuilder.UseSqlServer(connectionString); } } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity() .HasMany(c => c.ShoppingLists) .WithOne() .HasForeignKey(sl => sl.CustomerId) .OnDelete(DeleteBehavior.Cascade); modelBuilder.Entity() .HasMany(sl => sl.ShoppingItems) .WithOne() .HasForeignKey(si => si.ShoppingListId) .OnDelete(DeleteBehavior.Cascade); } } }