Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove order is unpredictable in Entity Framework

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?

like image 997
Nestor Avatar asked Oct 19 '22 01:10

Nestor


1 Answers

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.

like image 140
usr Avatar answered Nov 03 '22 17:11

usr