RobertoCarlos Melgar

RobertoCarlos Melgar

  • 1.6k
  • 159
  • 10.2k

Delete and save in table from Entity Framework

Apr 29 2020 12:56 PM
Hello friends, good morning.
I have the following drawback, a many-to-many table.
works perfectly up to here, I hope it is well implemented
I show the image
 
 I enter this data in this way
 
 now i want to remove a rule from a certain profile
 
 in this case remove the Employee profile, Create Client and Edit Client. The idea I have is to delete all the rules assigned to the employee and then again enter the new rules (In this case only one rule)
 
I did this method
 
  1. public static void InsertarPerfilRegla(tbltransPerfilRegla tbltransPerfilRegla)  
  2.         {  
  3.             using (GourmetEntities db = new GourmetEntities())  
  4.             {  
  5.                  
  6.                 db.tbltransPerfilReglas.RemoveRange(db.tbltransPerfilReglas.Where(x => x.Perfil_Id == tbltransPerfilRegla.Perfil_Id));  
  7.                 db.SaveChanges();  
  8.                 db.tbltransPerfilReglas.Add(tbltransPerfilRegla);  
  9.                 db.SaveChanges();  
  10.             }  
  11.               
  12.         }  
When I only run the code block
 
  1. db.tbltransPerfilReglas.RemoveRange(db.tbltransPerfilReglas.Where(x => x.Perfil_Id == tbltransPerfilRegla.Perfil_Id));    
  2.                db.SaveChanges();    
Works correctly
But when I run both codes it shows me an error
 
 
 This is the code in my Button
 
  1. private void TsbGuardar_Click(object sender, EventArgs e)  
  2.         {  
  3.             tbltransPerfilRegla tbltransPerfilRegla = new tbltransPerfilRegla();  
  4.             using (GourmetEntities db = new GourmetEntities())  
  5.             {  
  6.                 tbltransPerfilRegla.Perfil_Id = (int)CboPerfiles.SelectedValue;  
  7.                 foreach (DataGridViewRow row in DatagridViewPerfilRegla.Rows)  
  8.                 {  
  9.                     if ((bool)row.Cells["Selected"].Value)  
  10.                     {  
  11.                         //MessageBox.Show(row.Cells[1].Value.ToString());  
  12.                         tbltransPerfilRegla.Regla_Id = (int)row.Cells[1].Value;  
  13.                     }  
  14.                     tbltransPerfilRegla.InsertarPerfilRegla(tbltransPerfilRegla);  
  15.                 }  
  16.             }  
  17.         }  
Please can you help me to solve this problem that I have, or can you tell me another way to do this please.
I thank you very much
Rob
 

Answers (2)