From d83b2bbc86cc125b2c39611209ede6e037620fe7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Raymond=20Lei=28=E9=9B=B7=E8=8F=A9=E5=AE=87=29?= Date: Wed, 5 Mar 2025 23:00:12 -0500 Subject: [PATCH] Refactor BloggingContext to ensure DbSet properties are non-nullable and add initialization method --- .../BloggingContext.cs" | 17 +++++++++++++++-- .../Program.cs" | 1 + 2 files changed, 16 insertions(+), 2 deletions(-) diff --git "a/\344\272\202\344\270\203\345\205\253\347\263\237/\344\272\202\344\270\203\345\205\253\347\263\237.DataAccessLayer/BloggingContext.cs" "b/\344\272\202\344\270\203\345\205\253\347\263\237/\344\272\202\344\270\203\345\205\253\347\263\237.DataAccessLayer/BloggingContext.cs" index 0499248..e095419 100644 --- "a/\344\272\202\344\270\203\345\205\253\347\263\237/\344\272\202\344\270\203\345\205\253\347\263\237.DataAccessLayer/BloggingContext.cs" +++ "b/\344\272\202\344\270\203\345\205\253\347\263\237/\344\272\202\344\270\203\345\205\253\347\263\237.DataAccessLayer/BloggingContext.cs" @@ -10,8 +10,8 @@ public class BloggingContext : DbContext //public static readonly BloggingContext Default = new BloggingContext(); //public required DbSet Blogs { get; set; } //public required DbSet? Posts { get; set; } - public DbSet? Blogs { get; set; } - public DbSet? Posts { get; set; } + public DbSet Blogs { get; set; } + public DbSet Posts { get; set; } public string? DbPath { get; } = string.Empty; public BloggingContext() @@ -42,6 +42,19 @@ public BloggingContext(BloggingContext context, string dbPath) DbPath = dbPath; } + public BloggingContext(string dbPath) + { + Initialize(); + DbPath = dbPath; + } + + + protected virtual void Initialize() + { + Blogs = Set(); + Posts = Set(); + } + //public BloggingContext(string dbPath) //{ // DbPath = dbPath; diff --git "a/\344\272\202\344\270\203\345\205\253\347\263\237/\344\272\202\344\270\203\345\205\253\347\263\237.DataAccessLayer/Program.cs" "b/\344\272\202\344\270\203\345\205\253\347\263\237/\344\272\202\344\270\203\345\205\253\347\263\237.DataAccessLayer/Program.cs" index b451b1f..1f70eab 100644 --- "a/\344\272\202\344\270\203\345\205\253\347\263\237/\344\272\202\344\270\203\345\205\253\347\263\237.DataAccessLayer/Program.cs" +++ "b/\344\272\202\344\270\203\345\205\253\347\263\237/\344\272\202\344\270\203\345\205\253\347\263\237.DataAccessLayer/Program.cs" @@ -25,6 +25,7 @@ public static async Task Main(string[] args) using (var scope = host.Services.CreateScope()) { await using var db = new BloggingContext(); + db.Database.EnsureCreated(); // Note: This sample requires the database to be created before running.