I have the following delete 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 db.SaveChanges()
is called, I get an exception:
The DELETE statement conflicted with the REFERENCE constraint "FK_Users_Groups". The conflict occurred in database "UserDB", table "dbo.Users", column 'Group_ID'. The statement has been terminated.
It seems that the Remove methods are called in a reverse (random) order. If I add another db.SaveChanges()
after RemoveRange()
, it (obviously) works okay.
How can I force the order of remove?
You need to teach EF the table relationships. It will then automatically order the DML operations for you. Declare the relationships in your model. For example, the user class should have a group property.
These properties are very useful in queries as well. Not sure how you made due without them. Writing joins manually is tedious.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With