protected virtual void CreateRoleAndPermissions(AppUserRole roleType) { var roleFromDatabase = _context.Roles .IgnoreQueryFilters() .FirstOrDefault(r => r.TenantId == null && r.Name == roleType.GetDescriptionFromValue()); if (roleFromDatabase == null) { roleFromDatabase = new Role(null, roleType.GetDescriptionFromValue(), roleType.GetDescriptionFromValue()) { IsStatic = true, IsDefault = false }; _context.Roles.Add(roleFromDatabase); _context.SaveChanges(); } var activeRolePermissions = _context.RolePermissions .Where(p => p.RoleId == roleFromDatabase.Id && p.IsGranted).ToList(); // Grant all permissions var permissionNames = StaticRolePermissions.RolePermissions.ContainsKey(roleType) ? StaticRolePermissions.RolePermissions[roleType] : new List <string>(); foreach (var permission in permissionNames) { if (activeRolePermissions.Any(p => p.Name == permission)) { continue; } _context.Permissions.Add( new RolePermissionSetting { TenantId = null, Name = permission, IsGranted = true, RoleId = roleFromDatabase.Id }); } // remove not applyable permissions foreach (var activePermission in activeRolePermissions) { if (!permissionNames.Contains(activePermission.Name)) { activePermission.IsGranted = false; } } _context.SaveChanges(); }