Gravinco
Gravinco

Reputation: 687

Datacontext.SaveChanges() adds unwanted records to database

I apologize in advance if I'm not clear about my issue but I'm working on a project I don't really understand yet, so feel free to ask to elaborate on a certain part.

Right now I'm working on a test that was already present in the project but didn't work correctly i.e. the data added to the database didn't get deleted and it still used code from before a rework when I wasn't assigned yet. At this moment the test works properly but after it has run there are records left in the database that shouldn't even have been added.

In the code, which you can find here http://pastebin.com/YzRqi7dt , you can see the test method. The records that are added in the TestInitialize are deleted properly but after finishing the test there are still 4 records too much in the database. 2 of them are copies of the ConexioContacts in the testmethod. I know it are copies because I noticed at a certain point during debugging that there were 8 contacts added instead of 4. The other 2 contacts that remain in the database look like they come from my Seed() method, but the Seed() method doesn't get called or anything.

The adding of these 4 records happens during the

List<Synchronizer<BaseContact, ExternalContact, ConexioContact>.ConexioEntitySyncContext> matches     =
            Synchronizer<BaseContact, ExternalContact, ConexioContact>
            .FindMatches(conexioEntities, externalEntities, _unitOfWork);

when it enters the DataContext.SaveChanges() in the background (discovered while debugging). The method above can be found here: http://pastebin.com/t9iMGB31 . The DataContext.SaveChanges() gets called in the UnitOfWork.SaveChanges() at the end of the method.

Hope this was clear, if not, please ask.

With kind regards, Gravinco

EDIT:

The transaction suggested by Wyatt Earp resolves the problem if I run my test but I still don't know how or why the error occurred, if someone could elaborate on this I would be very grateful.

Upvotes: 1

Views: 160

Answers (1)

Wyatt Earp
Wyatt Earp

Reputation: 1823

One thing you could do is to wrap all of the work inside of a transaction and roll it back when you're done. This should keep any changes from hitting the database. Also, it might help locate the issue, if it is possibly coming from a different test or something...

Add a TransactionScope transaction; object to your test class and at the beginning of your TestInit() method, just do transaction = new TransactionScope(). Then, you can replace everything in your CleanTest() method with transaction.Dispose();

Upvotes: 3

Related Questions