Most efficient way to update with LINQ to SQL

前端 未结 6 1304
臣服心动
臣服心动 2020-12-28 16:50

Can I update my employee record as given in the function below or do I have to make a query of the employee collection first and then update the data?

  pub         


        
6条回答
  •  不思量自难忘°
    2020-12-28 17:30

    You cannot attach a modified entity to a DataContext when there is no RowVersion column. Instead you could store original entity in your application as long as maintaining a copy for data changes. Then when changes need to be saved you could attach original entity to a DataContext, change its values to match the modified entity values and submit changes.

    Here is an example:

    public int updateEmployee(App3_EMPLOYEE employee, App3_EMPLOYEE originalEmployee)
    {
        DBContextDataContext db = new DBContextDataContext();
        db.App3_EMPLOYEEs.Attach(originalEmployee);
    
        // TODO: Copy values from employee to original employee
    
        db.SubmitChanges();
        return employee.PKEY;
    }
    

    Update:

    There is a table in the database with columns ID, Name, Notes

    // fetch an employee which will not be changed in the application
    Employee original;
    using(var db = new TestDbDataContext())
    {
      original = db.Employees.First(e => e.ID == 2);
    }
    
    // create an instance to work with
    var modified = new Employee {ID = original.ID, Name = original.Name, Notes = original.Notes};
    
    // change some info
    modified.Notes = string.Format("new notes as of {0}", DateTime.Now.ToShortTimeString());  
    // update
    using(var db = new TestDbDataContext())
    {
      db.Employees.Attach(original);
      original.Notes = modified.Notes;
      db.SubmitChanges();
    }
    

提交回复
热议问题