acme deepak

acme deepak

  • NA
  • 30
  • 588

C# code to me made better with Lambda expressions

Jan 15 2020 7:44 PM
I have a C# code that will perform CRUD operations on data into a grid view. I need to make it work with the lambda expressions. Please find the below code and help me further. I have no prior knowledge of regular expressions. I have given all the methods that need to be converted to Regular expressions and made better if possible at all angles. Please help me with this.
  1. public IQueryable<Student> studentsGrid_GetData()    
  2. {    
  3.     SchoolContext db = new SchoolContext();    
  4.     var query = db.Students.Include(s => s.Enrollments.Select(e => e.Course));    
  5.     return query;    
  6. }    
  7.     
  8. // The id parameter name should match the DataKeyNames value set on the control    
  9. public void studentsGrid_UpdateItem(int id)    
  10. {    
  11.     ContosoUniversityModelBinding.Models.Student item = null;    
  12.     // Load the item here, e.g. item = MyDataLayer.Find(id);    
  13.     if (item == null)    
  14.     {    
  15.         // The item wasn't found    
  16.         ModelState.AddModelError("", String.Format("Item with id {0} was not found", id));    
  17.         return;    
  18.     }    
  19.     TryUpdateModel(item);    
  20.     if (ModelState.IsValid)    
  21.     {    
  22.         // Save changes here, e.g. MyDataLayer.SaveChanges();    
  23.     
  24.     }    
  25. }    
  26.     
  27. public void studentsGrid_UpdateItem(int studentID)    
  28. {    
  29.     using (SchoolContext db = new SchoolContext())    
  30.     {    
  31.         Student item = null;    
  32.         item = db.Students.Find(studentID);    
  33.         if (item == null)    
  34.         {    
  35.             ModelState.AddModelError("",     
  36.               String.Format("Item with id {0} was not found", studentID));    
  37.             return;    
  38.         }    
  39.     
  40.         TryUpdateModel(item);    
  41.         if (ModelState.IsValid)    
  42.         {    
  43.             db.SaveChanges();    
  44.         }    
  45.     }    
  46. }    
  47.     
  48. public void studentsGrid_DeleteItem(int studentID)    
  49. {    
  50.     using (SchoolContext db = new SchoolContext())    
  51.     {    
  52.         var item = new Student { StudentID = studentID };    
  53.         db.Entry(item).State = EntityState.Deleted;    
  54.         try    
  55.         {    
  56.             db.SaveChanges();    
  57.         }    
  58.         catch (DbUpdateConcurrencyException)    
  59.         {    
  60.             ModelState.AddModelError("",     
  61.               String.Format("Item with id {0} no longer exists in the database.", studentID));    
  62.         }    
  63.     }    
  64. }  

Answers (2)