51 lines
1.8 KiB
C#
51 lines
1.8 KiB
C#
|
|
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<DatabaseContext> options) : base(options) { }
|
|
public virtual DbSet<Customer> Customers { get; set; }
|
|
public virtual DbSet<ShoppingList> ShoppingLists { get; set; }
|
|
public virtual DbSet<ShoppingItem> 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<Customer>()
|
|
.HasMany(c => c.ShoppingLists)
|
|
.WithOne()
|
|
.HasForeignKey(sl => sl.CustomerId)
|
|
.OnDelete(DeleteBehavior.Cascade);
|
|
|
|
|
|
modelBuilder.Entity<ShoppingList>()
|
|
.HasMany(sl => sl.ShoppingItems)
|
|
.WithOne()
|
|
.HasForeignKey(si => si.ShoppingListId)
|
|
.OnDelete(DeleteBehavior.Cascade);
|
|
}
|
|
}
|
|
}
|