c# - Remove order is unpredictable in Entity Framework -


i have following delete method in entity framework code first project:

var selectedid = selectedgroup.id; var users = (from user in db.users                user.group_id == selectedid                select user); db.users.removerange(users);  db.groups.attach(selectedgroup); db.groups.remove(selectedgroup); db.savechanges(); 

these 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() called, exception:

the delete statement conflicted reference constraint "fk_users_groups". conflict occurred in database "userdb", table "dbo.users", column 'group_id'. statement has been terminated.

it seems remove methods called in reverse (random) order. if add another db.savechanges() after removerange(), (obviously) works okay.

how can force order of remove?

you need teach ef table relationships. automatically order dml operations you. declare relationships in model. example, user class should have group property.

these properties useful in queries well. not sure how made due without them. writing joins manually tedious.


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -