This is a migrated thread and some comments may be shown as answers.

update the database by copying an object...

1 Answer 47 Views
Development (API, general questions)
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
julien test
Top achievements
Rank 1
julien test asked on 14 Dec 2009, 10:47 AM
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.

1 Answer, 1 is accepted

Sort by
0
Damyan Bogoev
Telerik team
answered on 14 Dec 2009, 03:58 PM
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.
Tags
Development (API, general questions)
Asked by
julien test
Top achievements
Rank 1
Answers by
Damyan Bogoev
Telerik team
Share this question
or