コード例 #1
0
        private PreferencesViewModel BuildPreferencesViewModel(string userId)
        {
            var subscriptionPreferences          = DbContext.UserPreferences.OfType <SubscriptionPreference>().Where(u => u.User.Id == userId).ToList();
            var subscriptionPreferenceViewModels = from description in _reflectionService.GetSubscriptionDescriptions()
                                                   from maybeNullPreference in subscriptionPreferences.Where(sp => sp.SubscriptionName == description.Name).DefaultIfEmpty()
                                                   orderby description.Name
                                                   select new SubscriptionPreferenceViewModel()
            {
                Id = maybeNullPreference?.Id,
                SubscriptionName        = description.Name,
                SubscriptionDescription = description.Description,
                IsSmsRequested          = maybeNullPreference?.IsSmsRequested ?? false,
                IsEmailRequested        = maybeNullPreference?.IsEmailRequested ?? false,
            };

            var viewModel = new PreferencesViewModel()
            {
                SubscriptionPreferences = subscriptionPreferenceViewModels.ToList()
            };

            return(viewModel);
        }
コード例 #2
0
        public ActionResult Edit(PreferencesViewModel viewModel)
        {
            var userId = User.GetUserId();

            if (!ModelState.IsValid)
            {
                return(PartialView("Edit", viewModel));
            }

            var user = DbContext.Users.Include(u => u.Preferences).First(u => u.Id == userId);

            var subscriptionPreferences = user.Preferences.OfType <SubscriptionPreference>()
                                          .Where(u => u.User.Id == userId)
                                          .ToDictionary(p => p.Id);

            foreach (var postedSubscriptionPreference in viewModel.SubscriptionPreferences)
            {
                SubscriptionPreference subscriptionPreference;
                if (postedSubscriptionPreference.Id == null ||
                    !subscriptionPreferences.TryGetValue(postedSubscriptionPreference.Id.Value, out subscriptionPreference))
                {
                    subscriptionPreference = DbContext.Set <SubscriptionPreference>().Add(new SubscriptionPreference()
                    {
                        SubscriptionName = postedSubscriptionPreference.SubscriptionName,
                        User             = user
                    });
                }

                subscriptionPreference.IsEmailRequested = postedSubscriptionPreference.IsEmailRequested;
                subscriptionPreference.IsSmsRequested   = postedSubscriptionPreference.IsSmsRequested;
            }

            DbContext.SaveChanges();

            return(Display());
        }