コード例 #1
0
 // Add Controller-Permissions to database
 private void InitializeControllerPermissions(List <ControllerPermissions> controllerPermissions, ContextDb context)
 {
     foreach (var controllerPermission in controllerPermissions)
     {
         // If controller already exsits, update it with permissions
         if (context.MvcControllers.Any(c => c.Name == controllerPermission.ControllerName))
         {
             var mvcController = context.MvcControllers.Include(p => p.Permissions).Single(c => c.Name == controllerPermission.ControllerName);
             foreach (var permission in controllerPermission.Permissions)
             {
                 // Add if permission does not already exist for controller
                 if (mvcController.Permissions?.Any(p => p.Name == permission) != true)
                 {
                     var newPermission = new Permission {
                         Name = permission, MvcController = mvcController
                     };
                     context.Permissions.Add(newPermission);
                     mvcController.Permissions.Add(newPermission);
                 }
             }
             context.MvcControllers.Update(mvcController);
         }
         // Else create a new controller and permissions
         else
         {
             var mvcController = new MvcController
             {
                 Name        = controllerPermission.ControllerName,
                 Permissions = new Collection <Permission>(),
             };
             foreach (var permission in controllerPermission.Permissions)
             {
                 if (!mvcController.Permissions.Any(p => p.Name == permission))
                 {
                     var newPermission = new Permission {
                         Name = permission, MvcController = mvcController
                     };
                     context.Permissions.Add(newPermission);
                     mvcController.Permissions.Add(newPermission);
                 }
             }
             context.MvcControllers.Add(mvcController);
         }
     }
     context.SaveChanges();
 }