3

In my LINQ to SQL generated classes I have some classes containing EntitySets.

Everything looks great until I need to modify the EntitySet (add, delete some relationships). I thought that it was going to work doing something like:

User.Actions = newUserActions;   //This is how I used it with NHibernate

Then when I try to submit changes, I may get a duplicate key exception, that means it is not clearing the old actions before assigning the new ones and some of them may be repeated; do I have to do it manually ?

What is the best way to do this (update the EntitySet) ? Suggestions?

Thnx

Carlos Castillo
  • 533
  • 2
  • 6
  • 12

3 Answers3

2

It appears that I have to do it manually. I mean first delete the relationships (EntitySet):

//The EntitySet is user.UserActions
DataBaseContext.UserActions.DeleteAllOnSubmit(user.UserActions);
DataBaseContext.SubmitChanges();

And after that, assign the "new" EntitySet:

user.UserActions.Assign(GetSelectedActions());
DataBaseContext.SubmitChanges();

I made it work doing that but... DO I have to apply 2 SubmitChanges() to database? Isn't it a better way to do it?

Carlos Castillo
  • 533
  • 2
  • 6
  • 12
  • I'd be surprised if there is no better way to do this so we submit only the mutated part of the object tree in one submission and without manually modifying it. Maybe [Automapper](http://automapper.org/) can be used here, but I haven't tried. – orad Oct 15 '16 at 23:51
1

Wouldn't this be easier?

user.UserActions.Clear();
user.UserActions.AddRange(GetSelectedActions());
context.SubmitChanges();
Sam
  • 6,167
  • 30
  • 39
0

In the SQL database relationships did you have cascade delete set? You need this set and the classes regenerating to resolve this.

Chris Butcher
  • 485
  • 5
  • 15