Friday, March 5, 2010

How to EndEdit before changes can be submitted with Entity Ria Service

In my application, i am using Silverlight, Prism and WCF Ria Service, when user ended edit a cell, value changes will be saved to server.

In the View, i used SelectedItem binding to track change of the entity:

<telerikGridView:RadGridView
    ItemsSource="{Binding Departments}"
    SelectedItem="{Binding Department, Mode=TwoWay}"
    ...
    >
</telerikGridView:RadGridView>

In the ViewModel, that is

public DepartmentEntity Department
{
	get { return department;}
	set { 
		department = value; 
        FirePropertyChanged("Department");
		
		if (department != value)
		{
			department.PropertyChanged += department_PropertyChanged;
		}
	}
}

void department_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
	if (e.PropertyName == "HasChanges" && !context.IsSubmitting)
    {
        context.SubmitChanges();
	}
}

After i change value in a Cell of RadGridView, the following exception is thrown:

Entity 'DepartmentEntity : 1' is currently being edited and has uncommitted changes. A call to BeginEdit must be followed by a call to EndEdit or CancelEdit before changes can be submitted.

The solution:

Before context.SubmitChanges(), i inserted the following code lines:

IEditableObject editableObject = departmentEntity as IEditableObject;
editableObject.EndEdit();

context.SubmitChanges();

Now, the method for entity property changed is:

void department_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
	if (e.PropertyName == "HasChanges" && !context.IsSubmitting)
    	{
		IEditableObject editableObject = ecranSelected as IEditableObject;
	        editableObject.EndEdit();

	        context.SubmitChanges();
	}
}
And my application work fine.