I have the following uninstall method in an Entity Framework Code First project:
var selectedID = selectedGroup.ID;
var users = (from user in db.Users
where user.Group_ID == selectedID
select user);
db.Users.RemoveRange(users);
db.Groups.Attach(selectedGroup);
db.Groups.Remove(selectedGroup);
db.SaveChanges();
These are the models:
public class Group
{
[Key]
public Guid ID { get; set; }
[Required]
public Guid Branch { get; set; }
}
public class User
{
[Key]
public Guid ID { get; set; }
[Required]
public Guid Group_ID { get; set; }
}
When called db.SaveChanges(), I get an exception:
The DELETE operation is contrary to the REFERENCE clause of "FK_Users_Groups". The conflict occurred in the database "UserDB", the table "dbo.Users", the column "Group_ID". Application completed.
It seems that the Remove methods are called in reverse (random) order. If I add more db.SaveChanges()after RemoveRange(), it (obviously) works fine.
How can I force delete an order?
source
share