update the database by copying an object...

2 posts, 0 answers
  1. julien test
    julien test avatar
    15 posts
    Member since:
    Oct 2009

    Posted 14 Dec 2009 Link to this post

    Hi,

    I noticed that when I tried to update the database in that way (copy an object to another), it does not work and the database is not updated

    public static void UpdateEmployee(Employee employee)  
    {  
        scope.Transaction.Begin();  
      
        Employee employeeToEdit = GetEmployeeById(employee.Id);  
        employeeToEdit = employee; // Copies emplyee's properties to employeeToEdit's properties    
      
        scope.Transaction.Commit();  
    }   

    But if I try to update the database by setting each property of the destination objet with the ones from the source object, the database gets updated...

    public static void UpdateEmployee(Employee employee)  
    {  
        scope.Transaction.Begin();  
      
        Employee employeeToEdit  = GetEmployeeById(employee.Id);  
        employeeToEdit.FirstName = employee.FirstName ;  
        employeeToEdit.LastName  = employee.LastName;  
      
        scope.Transaction.Commit();  
    }   


    Is it possible to simply copy the source object to the destination object ? That would save the hassle of setting each property one by one...

    Thanks for your help.

    Regards.

  2. Damyan Bogoev
    Admin
    Damyan Bogoev avatar
    581 posts

    Posted 14 Dec 2009 Link to this post

    Hello julien test,

    There is an easier approach but it is only relevant if the object you want to update from is loaded from an object scope (is not new) and this scope is still alive. Then you can just commit the scope's transaction and the changes will be persisted:
    public static void UpdateEmployee(Employee employee)
    {
        IObjectScope scope = Database.GetContext(employee) as IObjectScope;
        if(scope != null)
          {
            if (!scope.Transaction.IsActive)
            {
                scope.Transaction.Begin();
            }
                scope.Transaction.Commit();
        }
    }

    However, if the employee object is new and is not associated with any object scope, the only option is to copy the values manually.

    Best wishes,
    Damyan Bogoev
    the Telerik team

    Instantly find answers to your questions on the new Telerik Support Portal.
    Watch a video on how to optimize your support resource searches and check out more tips on the blogs.
  3. DevCraft banner
Back to Top