From 09735e6103ec19d1dab05888e890e450c594c36f Mon Sep 17 00:00:00 2001 From: Syndamia Date: Wed, 12 May 2021 14:36:17 +0300 Subject: Improved the way in which database objects are created on startup --- ExamTemplate/Common/RoleConst.cs | 13 +++++++++++-- ExamTemplate/Web/Startup.cs | 28 +++++++++++++++++++++------- 2 files changed, 32 insertions(+), 9 deletions(-) diff --git a/ExamTemplate/Common/RoleConst.cs b/ExamTemplate/Common/RoleConst.cs index 3f0dfb7..7d72fea 100644 --- a/ExamTemplate/Common/RoleConst.cs +++ b/ExamTemplate/Common/RoleConst.cs @@ -1,8 +1,17 @@ +using System.Collections.Generic; + namespace ExamTemplate.Common { public static class RoleConst { - public static string User = "User"; - public static string Admin = "Administrator"; + public const string User = "User"; + public const string Admin = "Administrator"; + + public static List GetAllNames() + { + return new List() { + User, Admin + }; + } } } diff --git a/ExamTemplate/Web/Startup.cs b/ExamTemplate/Web/Startup.cs index c294566..691d60f 100644 --- a/ExamTemplate/Web/Startup.cs +++ b/ExamTemplate/Web/Startup.cs @@ -103,17 +103,31 @@ namespace ExamTemplate.Web dbContext.Database.Migrate(); var roleManager = (RoleManager>)serviceScope.ServiceProvider.GetService(typeof(RoleManager>)); - if (!dbContext.Roles.Any(x => x.Name == RoleConst.User)) + foreach (string name in RoleConst.GetAllNames()) { - IdentityRole userRole = new() { Name = RoleConst.User }; - roleManager.CreateAsync(userRole).Wait(); + if (!dbContext.Roles.Any(x => x.Name == name)) + { + IdentityRole role = new IdentityRole() { Name = name }; + roleManager.CreateAsync(role).Wait(); + } } - if (!dbContext.Roles.Any(x => x.Name == RoleConst.Admin)) + + /* If you want to create some custom database values at startup + * uncomment the following code + * and replace OBJCONST_ with your static class with constants (e.g. RoleConst) + * replace OBJS_ with the name of the DbSet of your database model (e.g. Roles) + * replace OBJ_ with the name of your database model (e.g. Role) + + foreach (string name in OBJCONST_.GetAllNames()) { - IdentityRole adminRole = new() { Name = RoleConst.Admin }; - roleManager.CreateAsync(adminRole).Wait(); + if (!dbContext.OBJS_.Any(x => x.Name == name)) + { + var entity = new OBJ_() { Id = Guid.NewGuid(), Name = name }; + dbContext.OBJS_.Add(entity); + dbContext.SaveChanges(); + } } - + */ } } } -- cgit v1.2.3