ShoppingApp/Weifer.Database.EF/DatabaseContext.cs

51 lines
1.8 KiB
C#
Raw Normal View History

2024-02-23 23:39:45 +01:00

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);
}
}
}