Initial push
This commit is contained in:
65
samples/SampleWebApi/Data/SampleDbContext.cs
Normal file
65
samples/SampleWebApi/Data/SampleDbContext.cs
Normal file
@@ -0,0 +1,65 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SampleWebApi.Models;
|
||||
|
||||
namespace SampleWebApi.Data;
|
||||
|
||||
public class SampleDbContext : DbContext
|
||||
{
|
||||
public SampleDbContext(DbContextOptions<SampleDbContext> options) : base(options)
|
||||
{
|
||||
}
|
||||
|
||||
public DbSet<Product> Products { get; set; } = null!;
|
||||
public DbSet<Order> Orders { get; set; } = null!;
|
||||
public DbSet<OrderItem> OrderItems { get; set; } = null!;
|
||||
public DbSet<Customer> Customers { get; set; } = null!;
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
// Product configuration
|
||||
modelBuilder.Entity<Product>(entity =>
|
||||
{
|
||||
entity.HasKey(p => p.Id);
|
||||
entity.Property(p => p.Name).IsRequired().HasMaxLength(200);
|
||||
entity.Property(p => p.Category).IsRequired().HasMaxLength(100);
|
||||
entity.Property(p => p.Price).HasPrecision(10, 2);
|
||||
entity.HasIndex(p => p.Category);
|
||||
entity.HasIndex(p => p.Price);
|
||||
});
|
||||
|
||||
// Order configuration
|
||||
modelBuilder.Entity<Order>(entity =>
|
||||
{
|
||||
entity.HasKey(o => o.Id);
|
||||
entity.Property(o => o.CustomerId).IsRequired().HasMaxLength(50);
|
||||
entity.Property(o => o.TotalAmount).HasPrecision(10, 2);
|
||||
entity.HasIndex(o => o.CustomerId);
|
||||
entity.HasIndex(o => o.OrderDate);
|
||||
entity.HasMany(o => o.Items)
|
||||
.WithOne(oi => oi.Order)
|
||||
.HasForeignKey(oi => oi.OrderId);
|
||||
});
|
||||
|
||||
// OrderItem configuration
|
||||
modelBuilder.Entity<OrderItem>(entity =>
|
||||
{
|
||||
entity.HasKey(oi => oi.Id);
|
||||
entity.Property(oi => oi.UnitPrice).HasPrecision(10, 2);
|
||||
entity.Property(oi => oi.TotalPrice).HasPrecision(10, 2);
|
||||
entity.HasIndex(oi => new { oi.OrderId, oi.ProductId });
|
||||
});
|
||||
|
||||
// Customer configuration
|
||||
modelBuilder.Entity<Customer>(entity =>
|
||||
{
|
||||
entity.HasKey(c => c.Id);
|
||||
entity.Property(c => c.Id).HasMaxLength(50);
|
||||
entity.Property(c => c.Name).IsRequired().HasMaxLength(200);
|
||||
entity.Property(c => c.Email).IsRequired().HasMaxLength(200);
|
||||
entity.HasIndex(c => c.Email).IsUnique();
|
||||
entity.HasMany(c => c.Orders)
|
||||
.WithOne()
|
||||
.HasForeignKey(o => o.CustomerId);
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user