This is the simplified partial pseudo code from the calling method:
using (var context = new ModelContext())
{
var transaction = context.Database.BeginTransaction();
try
{
// Delete stuff here
Users.DeleteAllByClient(context, clientToDelete.ClientId);
// And delete stuff here
transaction.Commit();
}
catch (Exception e)
{
transaction.Rollback();
return;
}
}
Take the example method, used to delete user details and their profile.
The ModelContext context is passed through to the method, which means that if the calling method does not commit transaction.Commit(); causing a rollback, this will not occur for the roles. They will have already been deleted.
Is it possible to add the Roles.RemoveUserFromRoles(item.User.UserName, roles); to the rollback?
I can't use TransactionScope (nested or not) as opposed to passing the context through.
public static void DeleteAllByClient(ModelContext context, int clientId)
{
// Users to delete
var models = context.UserDetails.Where(o => o.ClientId == clientId).ToList();
// list of user profiles
List<UserProfile> userProfileList = new List<UserProfile>();
foreach (var item in models)
{
var userProfile = context.UserProfiles.FirstOrDefault(o => o.UserId == item.UserId);
var roles = Roles.GetRolesForUser(userProfile.UserName);
// these need to roll back if commit doesn't happen
Roles.RemoveUserFromRoles(item.User.UserName, roles);
userProfileList.Add(userProfile);
}
if (models.Count > 0)
{
context.UserDetails.BulkDelete(models); // db tables specified for clarity
context.UserProfiles.BulkDelete(userProfileList);
}
}