Skip to content

Instantly share code, notes, and snippets.

@evgomes
Last active January 28, 2019 19:25
Show Gist options
  • Save evgomes/2cd77d33f36c25cff2850a4bcc78acd5 to your computer and use it in GitHub Desktop.
Save evgomes/2cd77d33f36c25cff2850a4bcc78acd5 to your computer and use it in GitHub Desktop.
Finished AppDbContext, from Supermarket API
using Microsoft.EntityFrameworkCore;
using Supermarket.API.Domain.Models;
namespace Supermarket.API.Persistence.Contexts
{
public class AppDbContext : DbContext
{
public DbSet<Category> Categories { get; set; }
public DbSet<Product> Products { get; set; }
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<Category>().ToTable("Categories");
builder.Entity<Category>().HasKey(p => p.Id);
builder.Entity<Category>().Property(p => p.Id).IsRequired().ValueGeneratedOnAdd();
builder.Entity<Category>().Property(p => p.Name).IsRequired().HasMaxLength(30);
builder.Entity<Category>().HasMany(p => p.Products).WithOne(p => p.Category).HasForeignKey(p => p.CategoryId);
builder.Entity<Category>().HasData
(
new Category { Id = 100, Name = "Fruits and Vegetables" }, // Id set manually due to in-memory provider
new Category { Id = 101, Name = "Dairy" }
);
builder.Entity<Product>().ToTable("Products");
builder.Entity<Product>().HasKey(p => p.Id);
builder.Entity<Product>().Property(p => p.Id).IsRequired().ValueGeneratedOnAdd();
builder.Entity<Product>().Property(p => p.Name).IsRequired().HasMaxLength(50);
builder.Entity<Product>().Property(p => p.QuantityInPackage).IsRequired();
builder.Entity<Product>().Property(p => p.UnitOfMeasurement).IsRequired();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment