1

Below is my common method to insert and update record,insert is working fine but update is not working for the below:

Code:

Public void Save(Employee e)
{
 using (var context = new SchoolManagementDataContext())
   {
      if(e.id > 0)  //For Update Part
      {
         var data=context.Employee.FirstorDefault(x=>x.EmployeeId==e.eid);
         data.Employeename=e.name;
         //rest other fileds to update.
         context.SubmitChanges();
      }
      else
      {
         context.Employee.InsertonSubmit(e);
         context.SubmitChanges();
      }
   }
}

I don't know why, but records are not getting updated.

I Love Stackoverflow
  • 6,738
  • 20
  • 97
  • 216
  • 1
    Can you launch the sql profiler and see if\what sql statement has been issued? – Martino Bordin Jan 11 '16 at 10:00
  • When you filter data by **ID** make an habit of using `SingleOrDefault` instead of `FirstorDefault`, `SingleOrDefault` is commonly used when **ID** is a primary key. You have bought model `Employee e` as parameter so in `If..Else` clause this must be `e.id` not `employee.id` – Suprabhat Biswal Jan 11 '16 at 10:09
  • @SuprabhatBiswal:yeah i have updated my question according to that but still issue is record is not updating – I Love Stackoverflow Jan 11 '16 at 10:37
  • Is Employee a model of the database table? It seems odd that you're using different variables names: `data.Employeename=e.name;`. Have you debugged to verify that a valid Employee record is being returned (the `data` variable)? – Ian Jan 13 '16 at 04:06
  • Yes Employee is model of database table and yes i have debug that valid employee is being returned in data variable – I Love Stackoverflow Jan 13 '16 at 05:26

1 Answers1

1

I think, you need UpdateOnSubmit() method. Try this:

Public void Save(Employee e)
{
 using (var context = new SchoolManagementDataContext())
   {
      if(e.id != null)  //For Update Part
      {
         var data=context.Employee.FirstorDefault(x=>x.EmployeeId==e.eid);
         data.Employeename=e.name;
         //rest other fileds to update.
         context.Employee.UpdateOnSubmit();
         context.SubmitChanges();
      }
      else
      {
         context.Employee.InsertonSubmit(e);
         context.SubmitChanges();
      }
   }
}

UpdateOnSubmit:

     public virtual void UpdateOnSubmit(T Entity)
     {
        myEntities.Attach(Entity);
        context.Entry(Entity).State = EntityState.Modified;
     }