コード例 #1
0
        public override void AddUsersToRoles(string[] usernames, string[] roleNames)
        {
            try
            {
                if (roleNames.Any(roleName => !RoleExists(roleName)))
                {
                    throw new ProviderException("Role name not found.");
                }

                foreach (var username in usernames)
                {
                    if (username.IndexOf(',') > 0)
                    {
                        throw new ArgumentException("Usernames cannot contain commas.");
                    }

                    if (roleNames.Any(roleName => IsUserInRole(username, roleName)))
                    {
                        throw new ProviderException("User is already in role.");
                    }
                }

                using (var con = SQLiteUtils.GetConnection(_connectionString))
                {
                    con.Open();

                    using (var transaction = con.BeginTransaction())
                    {
                        using (var cmd = con.CreateCommand())
                        {
                            cmd.CommandText = "INSERT INTO [aspnet_UsersInRoles] (" +
                                              "UserId, RoleId" +
                                              ") VALUES (" +
                                              "@UserId, @RoleId" +
                                              ")";

                            foreach (var username in usernames)
                            {
                                foreach (var roleName in roleNames)
                                {
                                    cmd.Parameters.Clear();

                                    cmd.Parameters.AddRange(new []
                                    {
                                        cmd.CreateParameter("@UserId", GetUserId(username)),
                                        cmd.CreateParameter("@RoleId", GetRoleId(roleName))
                                    });

                                    cmd.ExecuteNonQuery();
                                }
                            }
                        }
                        transaction.Commit();
                    }
                }
            }
            catch (SQLiteException ex)
            {
                if (!WriteExceptionsToEventLog)
                {
                    throw;
                }
                EventLogger.WriteToEventLog(ex, "AddUsersToRoles");
            }
        }