public ActionResult Index() { using (var ctx = new LunchContext()) { var today = DateTime.Now.Date; var user = ctx.Users.SingleOrDefault(u => u.EmailAddress == User.Identity.Name); var model = new HomeIndexViewModel { DictatorshipViewModels = new List<HomeIndexDictatorshipViewModel>() }; foreach (var dictatorship in user.Dictatorships) { var places = ctx.Places.Where(p => p.Dictatorship.Id == dictatorship.Id).ToList(); var dictatorshipModel = new HomeIndexDictatorshipViewModel() { Id = dictatorship.Id, Name = dictatorship.Name, Places = places.Select(p => new PlaceViewModel { ImageUrl = p.ImageUrl, Name = p.Name, Id = p.Id }) .ToList() }; if (dictatorshipModel.Places.Any()) { var selection = ctx.PlaceSelections.SingleOrDefault(s => s.Date == today && s.Place.Dictatorship.Id == dictatorship.Id); if (selection == null) { var rand = new Random(); selection = new PlaceSelection { Date = today, Place = places[rand.Next(places.Count)] }; ctx.PlaceSelections.Add(selection); ctx.SaveChanges(); } var selectedPlace = dictatorshipModel.Places.Single(p => p.Id == selection.Place.Id); selectedPlace.IsSelected = true; dictatorshipModel.SelectedPlace = selectedPlace.Name; } model.DictatorshipViewModels.Add(dictatorshipModel); } return this.View(model); } }
public ActionResult Create(DictatorshipViewModel viewModel) { if (!ModelState.IsValid) { return this.View(viewModel); } using (var ctx = new LunchContext()) { var user = ctx.Users.SingleOrDefault(u => u.EmailAddress == User.Identity.Name); var dictatorship = new Dictatorship { Name = viewModel.Name, ImageUrl = viewModel.ImageUrl, Users = new Collection<User> { user } }; ctx.Dictatorships.Add(dictatorship); ctx.SaveChanges(); } this.TempData["Message"] = WebCommon.DictatorshipAdded; return this.View(new DictatorshipViewModel()); }