aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSyndamia <kamen.d.mladenov@protonmail.com>2021-05-12 14:36:17 +0300
committerSyndamia <kamen.d.mladenov@protonmail.com>2021-05-12 14:36:17 +0300
commit09735e6103ec19d1dab05888e890e450c594c36f (patch)
tree13a8ac7517642a5cd30981adbd79b04195a90556
parentfc43ff3c98bad3f0c6df31dddefd192bdab9a77f (diff)
downloadit-kariera-exam-template-09735e6103ec19d1dab05888e890e450c594c36f.tar
it-kariera-exam-template-09735e6103ec19d1dab05888e890e450c594c36f.tar.gz
it-kariera-exam-template-09735e6103ec19d1dab05888e890e450c594c36f.zip
Improved the way in which database objects are created on startup
-rw-r--r--ExamTemplate/Common/RoleConst.cs13
-rw-r--r--ExamTemplate/Web/Startup.cs28
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<string> GetAllNames()
+ {
+ return new List<string>() {
+ 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<IdentityRole<Guid>>)serviceScope.ServiceProvider.GetService(typeof(RoleManager<IdentityRole<Guid>>));
- if (!dbContext.Roles.Any(x => x.Name == RoleConst.User))
+ foreach (string name in RoleConst.GetAllNames())
{
- IdentityRole<Guid> userRole = new() { Name = RoleConst.User };
- roleManager.CreateAsync(userRole).Wait();
+ if (!dbContext.Roles.Any(x => x.Name == name))
+ {
+ IdentityRole<Guid> role = new IdentityRole<Guid>() { 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<Guid> 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();
+ }
}
-
+ */
}
}
}