From b851fd937a4e24cc1cfc42ee0f5d6bdaf163f2e6 Mon Sep 17 00:00:00 2001 From: Jason Zhu Date: Wed, 16 Mar 2022 23:04:30 +1100 Subject: [PATCH] 10.3 Definig EF Core models -> Adding tables to the Northwind database context class --- .../WorkingWithEFCore/Northwind.cs | 31 ++++++++++++++++--- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/Chapter10/WorkingWithEFCore/WorkingWithEFCore/Northwind.cs b/Chapter10/WorkingWithEFCore/WorkingWithEFCore/Northwind.cs index 9476a3b..82c02c5 100644 --- a/Chapter10/WorkingWithEFCore/WorkingWithEFCore/Northwind.cs +++ b/Chapter10/WorkingWithEFCore/WorkingWithEFCore/Northwind.cs @@ -1,9 +1,14 @@ using Microsoft.EntityFrameworkCore; using static System.Console; + namespace Packt.Shared; public class Northwind : DbContext { + // These properties map to tables in database + public DbSet? Categories { get; set; } + public DbSet? Products { get; set; } + protected override void OnConfiguring( DbContextOptionsBuilder optionsBuilder) { @@ -17,10 +22,28 @@ public class Northwind : DbContext else { string connection = "Data Source=.;" + - "Initial Catalog=Northwind;" + - "Integrated Security=true;" + - "MultipleActiveResultSets=true;"; + "Initial Catalog=Northwind;" + + "Integrated Security=true;" + + "MultipleActiveResultSets=true;"; optionsBuilder.UseSqlServer(connection); } } -} + + protected override void OnModelCreating( + ModelBuilder modelBuilder) + { + // example of using Fluent API instead of attributes + // // to limit the length of a category name to 15 + modelBuilder.Entity() + .Property(category => category.CategoryName) + .IsRequired() // NOT NULL + .HasMaxLength(15); + if (ProjectConstants.DatabaseProvider == "SQLite") + { + // added to "fix" the lack of decimal support in SQLite + modelBuilder.Entity() + .Property(product => product.Cost) + .HasConversion(); + } + } +} \ No newline at end of file