Adam Adam - 2 months ago 33
C# Question

Adding and removing data from the db using Entity Framework

I have several tables in the DB and I want to remove all the data and repopulate the tables and only then perform a save changes (because in case the save fails I want to return to the old data).

when I remove the data from the DB and then try to add the data into the DB it fails and says "Adding a relationship with an entity which is in the Deleted state is not allowed.", but when I remove the data then save and then add the new data and saves again, everything works fine..

here is my code if it helps understanding the problem

// create the new data
SomeDataHolder data = ... ;
// save some data to re-enter back after changes
List<User> usersSave = ctx.Users.ToList();
List<UserPreferences> userPrefsSave = ctx.UserPreferences.ToList();

//clear DB
ctx.UserCourses.RemoveRange(ctx.UserCourses);
ctx.Users.RemoveRange(ctx.Users);
ctx.Specializtions.RemoveRange(ctx.Specializtions);
ctx.Course_Predecessor.RemoveRange(ctx.Course_Predecessor);
ctx.Courses.RemoveRange(ctx.Courses);
ctx.Departments.RemoveRange(ctx.Departments);
ctx.GroupsDetails.RemoveRange(ctx.GroupsDetails);
ctx.LinkTable.RemoveRange(ctx.LinkTable);


this next line makes everything works, without this line the code will fail on next save

// ctx.SaveChanges();

updateDepartmentsCoursesSpecialization(ctx, data.Specializations);
updateCoursePredecessorsAndParallel(ctx, data.Predecessors);
updateGroupDetails(ctx, data.GroupDetails);
updateLectureToPractice(ctx, data.LinkLectureWithPractice);
ctx.Users.AddRange(usersSave);
ctx.UserPreferences.AddRange(userPrefsSave);

ctx.SaveChanges();

Answer

Here you have to use Transaction.B'cos you're doing more than one atomic operation on your code base.By using Transaction where you can Combine several operations into one transaction within the same context.If there is any failure within the transaction then all will be roll-backed.

Transaction code snippet is like this :

 using (var ctx = new MyContext()) 
            { 
                using (var dbContextTransaction = ctx.Database.BeginTransaction()) 
                { 
                    try 
                    { 
                        //1st operations here
                        ctx.GroupsDetails.RemoveRange(ctx.GroupsDetails);
                        ctx.LinkTable.RemoveRange(ctx.LinkTable);
                        ctx.SaveChanges(); 

                        //2nd operations here
                        ctx.Users.AddRange(usersSave);
                        ctx.UserPreferences.AddRange(userPrefsSave);
                        ctx.SaveChanges();

                        dbContextTransaction.Commit(); 
                    } 
                    catch (Exception) 
                    { 
                        dbContextTransaction.Rollback(); 
                    } 
                } 
            } 

You can refer this for more info : Working with Transactions