public void Should_FailValidation_When_PhoneNumberIsNull() { // Arrange var restaurantProfileValidator = new RestaurantProfileValidator(); var restaurantProfile = new RestaurantProfile() { PhoneNumber = null, Address = new Address() { Street1 = "1250 Bellflower Blvd", City = "Long Beach", State = "CA", Zip = 90840 }, GeoCoordinates = new GeoCoordinates() { Longitude = 33.7838, Latitude = -118.1141 } }; // Act var result = restaurantProfileValidator.Validate(restaurantProfile, ruleSet: "CreateUser"); var isValid = result.IsValid; // Assert isValid.Should().Be(false); }
/// <summary> /// Constructor for CreateRestaurantPostLogicValidationStrategy. /// <para> /// @author: Jennifer Nguyen /// @update: 03/20/2018 /// </para> /// </summary> /// <param name="userAccount"></param> /// <param name="securityQuestions"></param> /// <param name="securityAnswerSalts"></param> /// <param name="passwordSalt"></param> /// <param name="claims"></param> /// <param name="userProfile"></param> /// <param name="restaurantProfile"></param> /// <param name="businessHours"></param> public CreateRestaurantPostLogicValidationStrategy(RestaurantProfile restaurantProfile, IList <BusinessHour> businessHours) { _restaurantProfile = restaurantProfile; _businessHours = businessHours; _businessHourValidator = new BusinessHourValidator(); }
public IActionResult RestaurantLogin(RestaurantProfile restaurantProfile) { // Check if customner exist var isCustomer = DineOutContext.RestaurantProfile.Where(r => r.Email == restaurantProfile.Email).FirstOrDefault(); if (isCustomer != null) { // Check to see if password matches string[] salt = isCustomer.PasswordHash.Split(":"); string newHashedPin = GenerateHash(restaurantProfile.PasswordHash, salt[0]); bool isValid = newHashedPin.Equals(salt[1]); if (isValid == true) { return(RedirectToAction("Menu")); } else { // Password does not match return(View("OwnerLogin")); } } else { return(View("OwnerLogin")); } }
public IActionResult RestaurantLogin(RestaurantProfile restaurantProfile) { // Check if customner exist var loggedInOwner = DineOutContext.RestaurantProfile.ToList().Find(c => c.Email == restaurantProfile.Email); if (loggedInOwner != null) { // Check to see if password matches string[] salt = loggedInOwner.PasswordHash.Split(":"); string newHashedPin = GenerateHash(restaurantProfile.PasswordHash, salt[0]); bool isValid = newHashedPin.Equals(salt[1]); if (isValid == true) { HttpContext.Session.SetString("restaurant_owner_Id", loggedInOwner.ToString()); TempData["message"] = "Successfully Logged In!"; return(RedirectToAction("Menu")); } else { // Password does not match TempData["message"] = "Invalid Login!"; return(View("OwnerLogin")); } } else { TempData["message"] = "User does not exist!"; return(View("OwnerLogin")); } }
public IActionResult Register(RestaurantProfile restaurantProfile, string firstPassword) { if (firstPassword != restaurantProfile.PasswordHash) { // Passwords don't match return(View("OwnerRegistration")); } // Generate Salt RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); byte[] buff = new byte[31]; rng.GetBytes(buff); string salt = Convert.ToBase64String(buff); // Generate Hash string hashed = GenerateHash(restaurantProfile.PasswordHash, salt); // Overwrite to delete the string passsword restaurantProfile.PasswordHash = String.Format("{0}:{1}", salt, hashed); try { //Try to save new customer DineOutContext.RestaurantProfile.Add(restaurantProfile); DineOutContext.SaveChanges(); return(RedirectToAction("Menu")); } catch { // Return to same view if cannot save to database return(RedirectToAction("OwnerRegistration")); } }
public IActionResult ForgotPassword(RestaurantProfile restaurantProfile, string firstPassword) { if (firstPassword != restaurantProfile.PasswordHash) { // New Password does not match TempData["message"] = "Password does not match!"; return(View()); } var isCustomer = DineOutContext.RestaurantProfile.Where(r => r.Email == restaurantProfile.Email).FirstOrDefault(); if (isCustomer != null) { // Customer exist string[] salt = isCustomer.PasswordHash.Split(":"); // Password match and will be updated string newSashed = GenerateHash(restaurantProfile.PasswordHash, salt[0]); // Overwrite to delete the string passsword isCustomer.PasswordHash = String.Format("{0}:{1}", salt[0], newSashed); DineOutContext.Update(isCustomer); DineOutContext.SaveChanges(); return(RedirectToAction("OwnerLogin")); } else { // Customer does not exist TempData["message"] = "User does not exit!"; return(View()); } }
public IActionResult SaveChanges(RestaurantProfile restaurantProfile) { if (ModelState.IsValid) { RestaurantProfile profileEntry = DineOutContext.RestaurantProfile .FirstOrDefault(r => r.RestaurantProfileId == restaurantProfile.RestaurantProfileId); if (profileEntry != null) { profileEntry.Email = restaurantProfile.Email; } DineOutContext.SaveChanges(); TempData["message"] = $"Your profile has been updated!"; } return(RedirectToAction("Menu")); }
public void Should_FailValidation_When_LatitudeIsEmpty() { // Arrange var restaurantProfileValidator = new RestaurantProfileValidator(); var restaurantProfile = new RestaurantProfile() { PhoneNumber = "(562)985-4111", Address = null, GeoCoordinates = new GeoCoordinates() { Longitude = 33.7838 } }; // Act var result = restaurantProfileValidator.Validate(restaurantProfile, ruleSet: "CreateUser"); var isValid = result.IsValid; // Assert isValid.Should().Be(false); }
public IActionResult ForgotPassword(RestaurantProfile restaurantProfile, string oldPassword, string firstPassword) { var isCustomer = DineOutContext.RestaurantProfile.Where(r => r.Email == restaurantProfile.Email).FirstOrDefault(); if (firstPassword != restaurantProfile.PasswordHash) { // New Password does not match return(View()); } if (isCustomer != null) { // Customer exist string[] salt = isCustomer.PasswordHash.Split(":"); string newHashedPin = GenerateHash(oldPassword, salt[0]); bool isValid = newHashedPin.Equals(salt[1]); if (isValid == true) { // Password match and will be updated string newSashed = GenerateHash(restaurantProfile.PasswordHash, salt[0]); // Overwrite to delete the string passsword isCustomer.PasswordHash = String.Format("{0}:{1}", salt[0], newSashed); DineOutContext.Update(isCustomer); DineOutContext.SaveChanges(); return(RedirectToAction("Menu")); } else { // Old password does not match return(View()); } } else { // Customer does not exist return(View()); } }
/// <summary> /// The StoreRestaurantUser method. /// Contains logic to store a restaurant user to the database. /// <para> /// @author: Jennifer Nguyen /// @updated: 03/13/2018 /// </para> /// </summary> /// <param name="userAccount"></param> /// <param name="passwordSalt"></param> /// <param name="securityQuestions"></param> /// <param name="securityAnswerSalts"></param> /// <param name="claims"></param> /// <param name="userProfile"></param> /// <param name="restaurantProfile"></param> /// <param name="businessHours"></param> /// <param name="foodPreferences"></param> /// <returns>ResponseDto with bool data</returns> public ResponseDto <bool> StoreRestaurantUser(UserAccount userAccount, PasswordSalt passwordSalt, UserClaims userClaims, UserProfile userProfile, RestaurantProfile restaurantProfile, IList <SecurityQuestion> securityQuestions, IList <SecurityAnswerSalt> securityAnswerSalts, IList <FoodPreference> foodPreferences, IList <BusinessHour> businessHours) { using (var dbContextTransaction = context.Database.BeginTransaction()) { try { // Add UserAccount context.UserAccounts.AddOrUpdate(userAccount); context.SaveChanges(); // Get Id from UserAccount var userId = (from account in context.UserAccounts where account.Username == userAccount.Username select account.Id).SingleOrDefault(); // Set UserId to dependencies passwordSalt.Id = userId; userClaims.Id = userId; userProfile.Id = userId; restaurantProfile.Id = userId; // Add FoodPreferences foreach (var foodPreference in foodPreferences) { foodPreference.UserId = userId; context.FoodPreferences.Add(foodPreference); context.SaveChanges(); } // Add SecurityQuestions foreach (var securityQuestion in securityQuestions) { securityQuestion.UserId = userId; context.SecurityQuestions.Add(securityQuestion); context.SaveChanges(); } // Get SecurityQuestions in database var queryable = (from question in context.SecurityQuestions where question.UserId == userId select question).ToList(); // Add SecurityAnswerSalts for (var i = 0; i < securityQuestions.Count; i++) { // Get SecurityQuestionId for each securityAnswerSalt var securityQuestionId = (from query in queryable where query.Question == securityQuestions[i].Question select query.Id).SingleOrDefault(); // Set SecurityQuestionId for SecurityAnswerSalt securityAnswerSalts[i].Id = securityQuestionId; // Add SecurityAnswerSalt context.SecurityAnswerSalts.Add(securityAnswerSalts[i]); context.SaveChanges(); } // Add PasswordSalt context.PasswordSalts.AddOrUpdate(passwordSalt); // Add UserClaims context.UserClaims.Add(userClaims); // Add UserProfile context.UserProfiles.Add(userProfile); // Add RestaurantProfile context.RestaurantProfiles.Add(restaurantProfile); context.SaveChanges(); // Add BusinessHours foreach (var businessHour in businessHours) { businessHour.RestaurantId = userId; context.BusinessHours.Add(businessHour); context.SaveChanges(); } // Add First Menu // Find the corresponding profile var dbRestaurantProfile = (from profile in context.RestaurantProfiles where profile.Id == userId select profile).SingleOrDefault(); var newMenu = new RestaurantMenu("Your First Menu", false, 0); newMenu.RestaurantProfile = dbRestaurantProfile; context.RestaurantMenus.Add(newMenu); context.Entry(dbRestaurantProfile).State = System.Data.Entity.EntityState.Unchanged; context.SaveChanges(); // Add First Menu Item // Find the corresponding menu var dbRestaurantMenu = (from menu in context.RestaurantMenus where menu.RestaurantId == restaurantProfile.Id select menu).SingleOrDefault(); var newMenuItem = new RestaurantMenuItem(itemName: "Your First Menu Item", itemPrice: 0, itemPicture: ConfigurationManager.AppSettings["DefaultURLMenuItemPath"], tag: "tag", description: "", isActive: false, flag: 0); newMenuItem.RestaurantMenu = dbRestaurantMenu; context.RestaurantMenuItems.Add(newMenuItem); context.Entry(dbRestaurantMenu).State = System.Data.Entity.EntityState.Unchanged; context.SaveChanges(); // Commit transaction to database dbContextTransaction.Commit(); // Return a true ResponseDto return(new ResponseDto <bool>() { Data = true }); } catch (Exception) { // Rolls back the changes saved in the transaction dbContextTransaction.Rollback(); // Return a false ResponseDto return(new ResponseDto <bool>() { Data = false, Error = GeneralErrorMessages.GENERAL_ERROR }); } } }
/// <summary> /// Instantiate domain model equivalent of Dto's /// <para> /// @author: Brian Fann /// @updated: 4/25/18 /// </para> /// </summary> /// <param name="dto">Dto to map</param> /// <param name="param">Parameter Object to map to</param> /// <returns></returns> private ResponseDto <bool> MapRestaurantDtoToModels(RegisterRestaurantDto dto, out UserAccount userAccount, out PasswordSalt passwordSalt, out UserClaims userClaims, out UserProfile userProfile, out IList <SecurityQuestion> securityQuestions, out IList <SecurityAnswerSalt> securityAnswerSalts, out RestaurantProfile restaurantProfile, out IList <BusinessHour> businessHours, out IList <FoodPreference> foodPreferences) { // Try to map user dto var mappingResult = MapUserDtoToModel(dto, out userAccount, out passwordSalt, out userProfile, out securityQuestions, out securityAnswerSalts); if (!mappingResult.Data) { restaurantProfile = null; foodPreferences = null; businessHours = null; userClaims = null; return(mappingResult); } restaurantProfile = new RestaurantProfile( phoneNumber: dto.RestaurantProfileDto.PhoneNumber, address: dto.RestaurantProfileDto.Address, details: dto.RestaurantProfileDto.Details); // Call GeocodeService to get geocoordinates of the restaurant var geocodeService = new GoogleGeocodeService(); var geocodeResponse = geocodeService.Geocode(restaurantProfile.Address); var dateTimeService = new DateTimeService(); businessHours = dto.BusinessHourDtos .Select(businessHourDto => new BusinessHour( timeZone: dto.TimeZone, day: businessHourDto.Day, openTime: dateTimeService.ConvertLocalMeanTimeToUtc(dateTimeService.ConvertTimeToDateTimeUnspecifiedKind(businessHourDto.OpenTime), dto.TimeZone), closeTime: dateTimeService.ConvertLocalMeanTimeToUtc(dateTimeService.ConvertTimeToDateTimeUnspecifiedKind(businessHourDto.CloseTime), dto.TimeZone))) .ToList(); foodPreferences = new List <FoodPreference>(); if (dto.FoodPreferences != null) { foodPreferences = dto.FoodPreferences.Select(foodPreference => new FoodPreference(foodPreference)).ToList(); } // Set user claims to be stored in UserClaims table var claimsFactory = new ClaimsFactory(); userClaims = new UserClaims(claimsFactory.Create(AccountTypes.Restaurant)); if (geocodeResponse.Error != null) { return(new ResponseDto <bool> { Data = false, Error = geocodeResponse.Error }); } restaurantProfile.GeoCoordinates = new GeoCoordinates(latitude: geocodeResponse.Data.Latitude, longitude: geocodeResponse.Data.Longitude); // Successful response return(new ResponseDto <bool>() { Data = true }); }
public ResponseDto <bool> EditProfile(RestaurantProfileDto restaurantProfileDto, string token) { var geocodeService = new GoogleGeocodeService(); var restaurantBusinessHourDtoService = new RestaurantBusinessHourDtoService(); var tokenService = new TokenService(); var editRestaurantProfilePreLogicValidationStrategy = new EditRestaurantUserProfilePreLogicValidationStrategy(restaurantProfileDto); var result = editRestaurantProfilePreLogicValidationStrategy.ExecuteStrategy(); if (result.Error != null) { return(new ResponseDto <bool> { Data = false, Error = GeneralErrorMessages.GENERAL_ERROR }); } // Retrieve account by username var userGateway = new UserGateway(); var userAccountResponseDto = userGateway.GetUserByUsername(tokenService.GetTokenUsername(token)); // Extrant user profile domain var userProfileDomain = new UserProfile { DisplayName = restaurantProfileDto.DisplayName }; var geocodeResponse = geocodeService.Geocode(restaurantProfileDto.Address); if (geocodeResponse.Error != null) { return(new ResponseDto <bool> { Data = false, Error = GeneralErrorMessages.GENERAL_ERROR }); } // Extract restaurant profile domain var restaurantProfileDomain = new RestaurantProfile( restaurantProfileDto.PhoneNumber, restaurantProfileDto.Address, restaurantProfileDto.Details) { GeoCoordinates = new GeoCoordinates(geocodeResponse.Data.Latitude, geocodeResponse.Data.Longitude) }; // Extract business hours domains var restaurantBusinessHourDtos = restaurantProfileDto.BusinessHours; // Call the RestaurantBusinessHourDtoService var convertedRestaurantBusinessHourDtos = restaurantBusinessHourDtoService.SetDateTimesFromStringTimes(restaurantBusinessHourDtos); // Extract restaurant menus if (restaurantProfileDto.RestaurantMenusList.Count == 0) { } var restaurantMenuDomains = restaurantProfileDto.RestaurantMenusList; // Execute update of database var profileGateway = new RestaurantProfileGateway(); var responseDtoFromGateway = profileGateway.EditRestaurantProfileById(userAccountResponseDto.Data.Id, userProfileDomain, restaurantProfileDomain, convertedRestaurantBusinessHourDtos, restaurantMenuDomains); return(responseDtoFromGateway); }
/// <summary> /// Returns restaurant profile dto inside response dto /// </summary> /// <param name="username"></param> /// <returns></returns> /// // move context up to here public ResponseDto <RestaurantProfileDto> GetRestaurantProfileById(int?id) { using (context) { var dbUserProfile = (from profile in context.UserProfiles where profile.Id == id select profile).SingleOrDefault(); var userProfileDomain = new UserProfile(dbUserProfile.Id, dbUserProfile.DisplayName, dbUserProfile.DisplayPicture); // Find restaurant associated with the ID var dbRestaurantProfile = (from restaurantProfile in context.RestaurantProfiles where restaurantProfile.Id == dbUserProfile.Id select restaurantProfile).SingleOrDefault(); var restaurantProfileDomain = new RestaurantProfile(dbRestaurantProfile.PhoneNumber, dbRestaurantProfile.Address, dbRestaurantProfile.Details); // Find restaurant's business hours var businessHourDtos = (from businessHour in context.BusinessHours where businessHour.RestaurantId == dbRestaurantProfile.Id select new RestaurantBusinessHourDto() { Id = businessHour.Id, Day = businessHour.Day, OpenDateTime = businessHour.OpenTime, CloseDateTime = businessHour.CloseTime, TimeZone = businessHour.TimeZone }).ToList(); IList <RestaurantMenuWithItems> restaurantMenusList = new List <RestaurantMenuWithItems>(); var dbRestaurantMenus = dbRestaurantProfile.RestaurantMenu; if (dbRestaurantMenus.Count > 0) { foreach (var menu in dbRestaurantMenus) { // Create the menu domain var menuDomain = new RestaurantMenu(menu.Id, menu.MenuName, menu.IsActive, menu.Flag); // Create the list for the menu items var menuItemDomains = new List <RestaurantMenuItem>(); // Then, find all menu items associated with each menu and turn that into a list var dbMenuItems = (from menuItems in context.RestaurantMenuItems where menuItems.MenuId == menu.Id select menuItems).ToList(); foreach (var item in dbMenuItems) { var menuItemDomain = new RestaurantMenuItem(item.Id, item.ItemName, item.ItemPrice, item.ItemPicture, item.Tag, item.Description, item.IsActive, item.Flag); menuItemDomains.Add(menuItemDomain); // Map menu items to menus in a dictionary } var restaurantMenuWithItems = new RestaurantMenuWithItems(menuDomain, menuItemDomains); restaurantMenusList.Add(restaurantMenuWithItems); } } else { restaurantMenusList = new List <RestaurantMenuWithItems>(); } ResponseDto <RestaurantProfileDto> responseDto = new ResponseDto <RestaurantProfileDto> { Data = new RestaurantProfileDto(userProfileDomain, restaurantProfileDomain, businessHourDtos, restaurantMenusList), Error = null }; return(responseDto); } }
/// <summary> /// Returns true if update process succeeds, false if fails /// </summary> /// <param name="restaurantProfileDto"></param> /// <returns></returns> public ResponseDto <bool> EditRestaurantProfileById(int?id, UserProfile userProfileDomain, RestaurantProfile restaurantProfileDomain, IList <RestaurantBusinessHourDto> RestaurantBusinessHourDtos, IList <RestaurantMenuWithItems> restaurantMenuDomains) { using (context) { using (var dbContextTransaction = context.Database.BeginTransaction()) { try { // Find profile associated with account var dbUserProfile = (from profile in context.UserProfiles where profile.Id == id select profile).SingleOrDefault(); // Find restaurant associated with profile var dbRestaurantProfile = dbUserProfile.RestaurantProfile; // Find restaurant's business hours var dbBusinessHours = dbRestaurantProfile.BusinessHours; // Then, find all menus associated with this restaurant and their menu items IList <RestaurantMenuWithItems> dbRestaurantMenusList = new List <RestaurantMenuWithItems>(); var dbRestaurantMenus = dbRestaurantProfile.RestaurantMenu; foreach (var menu in dbRestaurantMenus) { // create the list for the menu items var dbMenuItemsList = new List <RestaurantMenuItem>(); // Then, find all menu items associated with each menu and turn that into a list var dbMenuItems = (from menuItems in context.RestaurantMenuItems where menuItems.MenuId == menu.Id select menuItems).ToList(); foreach (var item in dbMenuItems) { dbMenuItemsList.Add(item); // Map menu items to menus in a dictionary } var dbRestaurantMenuWithItems = new RestaurantMenuWithItems(menu, dbMenuItemsList); dbRestaurantMenusList.Add(dbRestaurantMenuWithItems); } // Update associated user profile dbUserProfile.DisplayName = userProfileDomain.DisplayName; context.SaveChanges(); // Update restaurant profile dbRestaurantProfile.PhoneNumber = restaurantProfileDomain.PhoneNumber; dbRestaurantProfile.Address = restaurantProfileDomain.Address; dbRestaurantProfile.Details = restaurantProfileDomain.Details; dbRestaurantProfile.GeoCoordinates = restaurantProfileDomain.GeoCoordinates; dbRestaurantProfile = restaurantProfileDomain; context.SaveChanges(); // Find the business hours on the database that have the same Ids as the new business hours foreach (var restaurantBusinessHourDto in RestaurantBusinessHourDtos) { Flag flag = restaurantBusinessHourDto.Flag; switch (flag) { case Flag.NotSet: break; case Flag.Add: // Reset flag restaurantBusinessHourDto.Flag = 0; var businessHourDomain = new BusinessHour(restaurantBusinessHourDto.TimeZone, restaurantBusinessHourDto.Day, restaurantBusinessHourDto.OpenDateTime, restaurantBusinessHourDto.CloseDateTime); dbBusinessHours.Add(businessHourDomain); context.SaveChanges(); break; case Flag.Edit: // find the corresponding businessHour by ID var dbBusinessHour = (from dbHour in context.BusinessHours where dbHour.Id == restaurantBusinessHourDto.Id select dbHour).SingleOrDefault(); dbBusinessHour.Day = restaurantBusinessHourDto.Day; dbBusinessHour.OpenTime = restaurantBusinessHourDto.OpenDateTime; dbBusinessHour.CloseTime = restaurantBusinessHourDto.CloseDateTime; dbBusinessHour.TimeZone = restaurantBusinessHourDto.TimeZone; context.SaveChanges(); break; case Flag.Delete: // Find the corresponding businessHour by ID dbBusinessHour = (from hour in context.BusinessHours where hour.Id == restaurantBusinessHourDto.Id select hour).SingleOrDefault(); context.BusinessHours.Remove(dbBusinessHour); context.SaveChanges(); break; } } // Update menu foreach (var restaurantMenuWithItems in restaurantMenuDomains) { Flag flag = restaurantMenuWithItems.RestaurantMenu.Flag; switch (flag) { case Flag.NotSet: break; case Flag.Add: restaurantMenuWithItems.RestaurantMenu.Flag = 0; restaurantMenuWithItems.RestaurantMenu.RestaurantMenuItems = new Collection <RestaurantMenuItem>(); dbRestaurantMenus.Add(restaurantMenuWithItems.RestaurantMenu); context.SaveChanges(); // Add the menu items inside the menu foreach (var menuItem in restaurantMenuWithItems.MenuItem) { // Find the corresponding menu var dbRestaurantMenu = (from menu in context.RestaurantMenus where menu.Id == restaurantMenuWithItems.RestaurantMenu.Id select menu).SingleOrDefault(); // Reset flag menuItem.Flag = 0; dbRestaurantMenu.RestaurantMenuItems.Add(menuItem); context.SaveChanges(); } break; case Flag.Edit: // Query for menu with the same ID var dbMenu = (from menu in context.RestaurantMenus where menu.Id == restaurantMenuWithItems.RestaurantMenu.Id select menu).SingleOrDefault(); dbMenu.MenuName = restaurantMenuWithItems.RestaurantMenu.MenuName; dbMenu.IsActive = restaurantMenuWithItems.RestaurantMenu.IsActive; context.SaveChanges(); break; case Flag.Delete: // Retrieves the menu from the db dbMenu = (from menu in context.RestaurantMenus where menu.Id == restaurantMenuWithItems.RestaurantMenu.Id select menu).SingleOrDefault(); context.RestaurantMenus.Remove(dbMenu); // Iterate through that menu's menu items foreach (var menuItem in restaurantMenuWithItems.MenuItem) { var dbMenuItem = (from item in context.RestaurantMenuItems where item.Id == menuItem.Id select item).SingleOrDefault(); context.RestaurantMenuItems.Remove(dbMenuItem); context.SaveChanges(); } break; } } // Update menu items foreach (var restaurantMenuWithItems in restaurantMenuDomains) { foreach (var menuItem in restaurantMenuWithItems.MenuItem) { Flag flag = menuItem.Flag; switch (flag) { case Flag.Add: // Find the corresponding menu var dbRestaurantMenu = (from menu in context.RestaurantMenus where menu.Id == restaurantMenuWithItems.RestaurantMenu.Id select menu).SingleOrDefault(); // Reset flag menuItem.Flag = 0; dbRestaurantMenu.RestaurantMenuItems.Add(menuItem); context.SaveChanges(); break; case Flag.Edit: // Query for menu item with the same ID var dbMenuItem = (from item in context.RestaurantMenuItems where item.Id == menuItem.Id select item).SingleOrDefault(); dbMenuItem.ItemName = menuItem.ItemName; dbMenuItem.ItemPicture = menuItem.ItemPicture; dbMenuItem.ItemPrice = menuItem.ItemPrice; dbMenuItem.Tag = menuItem.Tag; dbMenuItem.Description = menuItem.Description; dbMenuItem.IsActive = menuItem.IsActive; context.SaveChanges(); break; case Flag.Delete: dbMenuItem = (from item in context.RestaurantMenuItems where item.Id == menuItem.Id select item).SingleOrDefault(); context.RestaurantMenuItems.Remove(dbMenuItem); context.SaveChanges(); break; } } } context.SaveChanges(); dbContextTransaction.Commit(); ResponseDto <bool> responseDto = new ResponseDto <bool> { Data = true, Error = null }; return(responseDto); } catch (Exception) { dbContextTransaction.Rollback(); ResponseDto <bool> responseDto = new ResponseDto <bool> { Data = false, Error = GeneralErrorMessages.GENERAL_ERROR }; return(responseDto); } } } }