From 4021889c650061510ab34f4879b979c293adc173 Mon Sep 17 00:00:00 2001 From: "jason.zhu" Date: Tue, 22 Jun 2021 16:00:20 +1000 Subject: [PATCH] Chap4: Scaffolding a Store Manager (add database initialization strategy) --- MvcMusicStore/Data/MusicStoreDB.cs | 26 +++++++++++++++++++++++++- MvcMusicStore/Global.asax.cs | 7 ++++++- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/MvcMusicStore/Data/MusicStoreDB.cs b/MvcMusicStore/Data/MusicStoreDB.cs index 5d7491d..bd91475 100644 --- a/MvcMusicStore/Data/MusicStoreDB.cs +++ b/MvcMusicStore/Data/MusicStoreDB.cs @@ -1,4 +1,5 @@ -using System; +using MvcMusicStore.Models; +using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; @@ -25,4 +26,27 @@ namespace MvcMusicStore.Data public System.Data.Entity.DbSet Genres { get; set; } } + + + public class MusicStoreDbInitializer + : DropCreateDatabaseAlways + { + protected override void Seed(MusicStoreDB context) + { + context.Artists.Add(new Artist { Name = "Al Di Meola" }); + + context.Genres.Add(new Genre { Name = "Jazz" }); + + context.Albums.Add(new Album + { + Artist = new Artist { Name = "Rush" }, + Genre = new Genre { Name = "Rock" }, + Price = 9.99m, + Title = "Caravan" + }); + base.Seed(context); + } + } + + } diff --git a/MvcMusicStore/Global.asax.cs b/MvcMusicStore/Global.asax.cs index 45a453d..e0267b4 100644 --- a/MvcMusicStore/Global.asax.cs +++ b/MvcMusicStore/Global.asax.cs @@ -1,5 +1,7 @@ -using System; +using MvcMusicStore.Data; +using System; using System.Collections.Generic; +using System.Data.Entity; using System.Linq; using System.Web; using System.Web.Mvc; @@ -8,10 +10,13 @@ using System.Web.Routing; namespace MvcMusicStore { + public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { + Database.SetInitializer(new MusicStoreDbInitializer()); + AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes);