Page 1 of 1

How to resolve conflicts

Posted: Thu 21 May 2009 14:51
by dilbert
Can you help me how to remove conflicted objects from Data Context?

For example if method SubmitChanges() failed (e.g. due to insertion of duplicate key), I don't know how to recover from this failure.
If I try to insert another object (with correct values) it fails again because it first tries to insert the previous object (with duplicate key).


See this example:

Code: Select all

CREATE TABLE `user_group` (
	id_user INT NOT NULL, 
	id_group INT NOT NULL, 
	PRIMARY KEY(id_user, id_group));

//With values:
INSERT INTO `user_group` VALUES (1,1), (2,1);

Code: Select all

UserGroup ug = new UserGroup();
ug.Id_user = 1;
ug.Id_group = 1;
try
{
	DB.UserGroups.InsertOnSubmit(ug);
	DB.SubmitChanges();     // fails - it's OK (duplicate key)
}
catch 
{
	// I need to remove the conflicted object from dataContext here
}


ug = new UserGroup();
ug.Id_user = 3;
ug.Id_group = 1;
try
{
	DB.UserGroups.InsertOnSubmit(ug);
	DB.SubmitChanges();     // fails with duplicate key (1,1) - but I want to insert only values (3,1)
}
catch {}

I suppose that there should be a 'Resolve' method to maintain the conflicts.

Thanks in advance for your help

Posted: Fri 22 May 2009 13:37
by AndreyR
You can call the DeleteOnSubmit() method for the object causing duplicate key error - this object will be deleted from context,
but not from the database (it's inserted but not posted).
As an alternative, you can use the SubmitChanges(ConflictMode.ContinueOnConflict) method.
You can find more information on it here:
http://msdn.microsoft.com/en-us/library/bb345081.aspx