Praveen Kumar

Praveen Kumar

  • NA
  • 235
  • 20.4k

Prevent from inserting duplicate records into the table

Jun 2 2020 3:48 AM
Controller : Create
  1. [HttpPost]  
  2. [ValidateAntiForgeryToken]  
  3. public ActionResult Create(UserDefinedFieldsViewModel model)  
  4. {  
  5. using (var dbContextScope = _dbContextScopeFactory.Create())  
  6. {  
  7. var deletedValues = model.Values.Where(v => v.UIStatus == "DELETE").ToList();  
  8. foreach (var deletedValue in deletedValues)  
  9. {  
  10. model.Values.Remove(deletedValue);  
  11. }  
  12. if (!model.IsFreeformTextValue)  
  13. {  
  14. if (model.Values == null || (model.Values.Count == 1 && model.Values.First().UIStatus == "TEMPLATE"))  
  15. {  
  16. ModelState.AddModelError("Values""Please enter at least one valid value.");  
  17. }  
  18. }  
  19. else  
  20. {  
  21. var userCodeType = attrRepo.Find(model.UserCodeTypeId);  
  22. if (!new string[] { "CO""CT" }.Contains(userCodeType.Code))  
  23. {  
  24. ModelState.AddModelError("IsFreeformTextValue""Freeform text values only allowed for Company and Contact attributes.");  
  25. }  
  26. else if (model.Values != null && model.Values.Where(v => v.UIStatus != "DELETE").Count() > 1)  
  27. {  
  28. ModelState.AddModelError("Values""No values can be specified if 'Allow Freeform Text Value' is checked.");  
  29. }  
  30. }  
  31. if (ModelState.IsValid)  
  32. {  
  33. try  
  34. {  
  35. User user = _Login.GetCurrentUser();  
  36. UserCode userCode = model;  
  37. userCode.CustomerId = GetCustomerId();  
  38. attrRepo.AddUserCode(userCode, user);  
  39. dbContextScope.SaveChanges();  
  40. return RedirectToAction("Index");  
  41. }  
  42. catch (Exception e)  
  43. {  
  44. if (e is DbUpdateException dbUpdateEx)  
  45. {  
  46. if (dbUpdateEx.InnerException != null && dbUpdateEx.InnerException.InnerException != null)  
  47. {  
  48. if (dbUpdateEx.InnerException.InnerException is SqlException sqlException)  
  49. {  
  50. switch (sqlException.Number)  
  51. {  
  52. case 2601: // Duplicated key row error  
  53. // Constraint violation exception  
  54. ModelState.AddModelError("""Error: You cannot create an attribute with the same name, type code as an existing attribute");  
  55. break;  
  56. default:  
  57. break;  
  58. }  
  59. }  
  60. }  
  61. }  
  62. else  
  63. {  
  64. ModelState.AddModelError("""An error occured saving the attribute.");  
  65. }  
  66. }  
  67. }  
  68. model.UserCodeTypes = SelectListItemHelper.UserCodeTypes();  
  69. }  
  70. return View(model);  
  71. }  
Controller :Edit
  1. [HttpPost]  
  2. [ValidateAntiForgeryToken]  
  3. public ActionResult Edit(UserDefinedFieldsViewModel model)  
  4. {  
  5. using (var dbContextScope = _dbContextScopeFactory.Create())  
  6. {  
  7. if (!model.IsFreeformTextValue)  
  8. {  
  9. if (model.Values == null || (model.Values.Where(v => v.UIStatus != "DELETE").Count() == 1 && model.Values.First().UIStatus == "TEMPLATE"))  
  10. {  
  11. ModelState.AddModelError("Values""Please enter at least one valid value.");  
  12. }  
  13. }  
  14. else  
  15. {  
  16. var userCodeType = attrRepo.Find(model.UserCodeTypeId);  
  17. if (!new string[] { "CO""CT" }.Contains(userCodeType.Code))  
  18. {  
  19. ModelState.AddModelError("IsFreeformTextValue""Freeform text values only allowed for Company and Contact attributes.");  
  20. }  
  21. else if (model.Values != null && model.Values.Where(v => v.UIStatus != "DELETE").Count() > 1)  
  22. {  
  23. model.IsFreeformTextValue = false;  
  24. ModelState.AddModelError("Values""No values can be specified if 'Allow Freeform Text Value' is checked.");  
  25. }  
  26. }  
  27. if (ModelState.IsValid)  
  28. {  
  29. model.Values.RemoveAll(x => x.UIStatus == "TEMPLATE" && x.Id == 0);  
  30. UserCode userCode = model;  
  31. // User user = _Login.GetCurrentUser();  
  32. try  
  33. {  
  34. foreach (var uvv in model.Values)  
  35. {  
  36. if (uvv.UIStatus == "DELETE")  
  37. {  
  38. try  
  39. {  
  40. attrRepo.DeleteUDFValidValue(uvv.Id, user);  
  41. var ucvv = userCode.UserCodeValidValues.Where(x => x.Id == uvv.Id).Single();  
  42. if (ucvv != null)  
  43. userCode.UserCodeValidValues.Remove(ucvv);  
  44. }  
  45. catch (RMRepositoryException re)  
  46. {  
  47. ModelState.AddModelError("Values", re.Message);  
  48. }  
  49. }  
  50. }  
  51. try  
  52. {  
  53. attrRepo.UpdateUserDefinedField(userCode, user);  
  54. catch (NotSupportedException)  
  55. {  
  56. throw;  
  57. }  
  58. dbContextScope.SaveChanges();  
  59. return RedirectToAction("Index");  
  60. }  
  61. catch (Exception e)  
  62. {  
  63. if (e is DbUpdateException dbUpdateEx)  
  64. {  
  65. if (dbUpdateEx.InnerException != null && dbUpdateEx.InnerException.InnerException != null)  
  66. {  
  67. if (dbUpdateEx.InnerException.InnerException is SqlException sqlException)  
  68. {  
  69. switch (sqlException.Number)  
  70. {  
  71. case 2601: // Duplicated key row error  
  72. // Constraint violation exception  
  73. ModelState.AddModelError("""Error: You cannot edit an attribute with the same name, type code as an existing attribute");  
  74. break;  
  75. default:  
  76. break;  
  77. }  
  78. }  
  79. }  
  80. }  
  81. else if (e is NotSupportedException nse)  
  82. {  
  83. ModelState.AddModelError("UserCodeTypeId", nse.Message);  
  84. }  
  85. else  
  86. {  
  87. ModelState.AddModelError("Values", e.Message);  
  88. }  
  89. }  
  90. }  
  91. var errors1 = ModelState.Values.SelectMany(v => v.Errors);  
  92. foreach (var a in errors1)  
  93. {  
  94. Debug.WriteLine(a.ErrorMessage);  
  95. }  
  96. //var errors = ModelState  
  97. // .Where(x => x.Value.Errors.Count > 0)  
  98. // .Select(x => new { x.Key, x.Value.Errors })  
  99. // .ToArray();  
  100. model.UserCodeTypes = SelectListItemHelper.UserCodeTypes();  
  101. }  
  102. return View(model);  
  103. }  
Repositry.cs for Edit
  1. public UserCode UpdateUserDefinedField(UserCode userCode, User user)  
  2. {  
  3. var dbCode = DbContext.UserCodes.Find(userCode.Id);  
  4. dbCode.Name = userCode.Name;  
  5. dbCode.Description = userCode.Description;  
  6. if (dbCode.UserCodeTypeId != userCode.UserCodeTypeId)  
  7. if (dbCode.UserCodeValidValues.Any(x=>x.UserCodeValues.Any()))  
  8. throw new NotSupportedException("You cannot change the attribute type because it has values in use.");  
  9. dbCode.UserCodeTypeId = userCode.UserCodeTypeId;  
  10. dbCode.IsFreeformTextValue = userCode.IsFreeformTextValue;  
  11. dbCode.IsMandatory = userCode.IsMandatory;  
  12. // Need to handle unique constraint violation  
  13. foreach (UserCodeValidValue ucvv in userCode.UserCodeValidValues)  
  14. {  
  15. UserCodeValidValue compare = dbCode.UserCodeValidValues.Where(x => x.Id == ucvv.Id).FirstOrDefault();  
  16. if (compare != null)  
  17. {  
  18. if (ucvv.Description != compare.Description || ucvv.CodeValue != compare.CodeValue)  
  19. {  
  20. compare.CodeValue = ucvv.CodeValue;  
  21. compare.Description = ucvv.Description;  
  22. UpdateWithUser(compare, user.UserId, "UpdateUserDefinedField");  
  23. }  
  24. }  
  25. else  
  26. {  
  27. ucvv.UserCode = dbCode;  
  28. AddWithUser(ucvv, user.UserId, "UpdateUserDefinedField");  
  29. }  
  30. }  
  31. UpdateWithUser(dbCode, user.UserId, "UpdateUserDefinedField");  
  32. return dbCode;  
  33. }  
 

Answers (2)