コード例 #1
0
        // **************************************
        // DeleteUser
        // **************************************
        public static void DeleteUser(int userId, bool takeOwnerShip = false)
        {
            using (var ctx = new SongSearchContext()) {
                var user = ctx.Users.SingleOrDefault(x => x.UserId == userId);

                if (user != null) {
                    if (user.UserId == Account.User().UserId) {
                        throw new ArgumentException("You cannot delete yourself");
                    }
                    if (user.IsSuperAdmin() && GetNumberOfUsersByAccessLevel(Roles.SuperAdmin) <= 1) {
                        throw new ArgumentException("You cannot delete the last SuperAdmin");
                    } else {

                        //if (takeOwnerShip) {
                        //    ctx.TakeOwnerShip(user);
                        //}
                        ctx.ReParentOrphans(user, user.ParentUser);

                        if (user.CreatedCatalogs.Count() > 0) {

                            var userCats = user.CreatedCatalogs.ToList();

                            foreach (var cat in userCats) {
                                ctx.DeleteCatalog(cat.CatalogId);
                            }
                        }

                        if (user.Invitation != null) {
                            ctx.Invitations.DeleteObject(user.Invitation);
                        }
                        //handled via cascade in db
                        //user.ActiveCartContents.ToList().ForEach(x => user.ActiveCartContents.Remove(x));
                        //user.UserCatalogRoles.ToList().ForEach(x => user.UserCatalogRoles.Remove(x));
                        var balance = user.PlanBalance; // ctx.PlanBalances.SingleOrDefault(x => x.PlanBalanceId == user.PlanBalanceId);
                        if (balance != null) {
                            balance.Users.Remove(user);
                            if (balance.Users.Count() == 0) {
                                ctx.Delete(balance);
                            } else {
                                ctx.RemoveFromUserBalance(user);
                                if (user.IsAnyAdmin()) {
                                    ctx.RemoveFromAdminBalance(user);
                                }
                            }
                        }
                        ctx.Users.DeleteObject(user);
                        ctx.SaveChanges();

                    }
                }
            }
        }