Print Page | Close Window

Unit Test And EntityManager.SaveChanges

Printed From: IdeaBlade
Category: DevForce
Forum Name: DevForce 2009
Forum Discription: For .NET 3.5
URL: http://www.ideablade.com/forum/forum_posts.asp?TID=1512
Printed Date: 14-Mar-2025 at 10:59pm


Topic: Unit Test And EntityManager.SaveChanges
Posted By: rkierner
Subject: Unit Test And EntityManager.SaveChanges
Date Posted: 08-Oct-2009 at 1:21pm

I'm trying to write a test and I'm running into an issue if I call SaveChanges on the EntityManager object. 

I get the following Exception:
 
"IdeaBlade.EntityModel.EntityManagerSaveException: This EntityManager is not currently connected - Reconnect before attempting to save."
 
Am I missing something or is there a work around for this.  My DomainModelEntityManager class extends from EntityManager and I pass in false to the constructor so that it can run disconnected.

        [TestMethod]
        public void TestMyMethod()
        {
            var mgr = new DomainModelEntityManager(false);
            var myObject = new MyClass { ID = 1};
            mgr.AttachEntity(myObject);
            var myService = new MyService(mgr);
            myService.PerformLogicAndSave(myObject);
        }

       public class MyService{
              public MyService(EntityManager myManager){
                     MyManager = myManager;
              }
              public void PerformLogicAndSave(MyClass myObject){
                     //Do Something to myObject
                     MyManager.SaveChanges();
              }
       }




Replies:
Posted By: GregD
Date Posted: 08-Oct-2009 at 6:36pm
SaveChanges() operates against the back-end datasource. Therefore you must be connected when performing a save.

You can instantiate an EntityManager, fill it with data from a local EntitySet file, make a bunch of changes, add new entities, save them to another local EntitySet file, etc., all while disconnected. But SaveChanges()? No.


Posted By: rkierner
Date Posted: 09-Oct-2009 at 5:23am
Am I missing the boat on what my method should do?  While live, I do want to persist the changes to the DB.  During testing, I obviously want to avoid hitting the DB.  Is there any guidance on how to structure methods/object hierarchy so that my code is testable?
 
Rick


Posted By: GregD
Date Posted: 09-Oct-2009 at 5:17pm
You can make your PerformLogicAndSave() method a little more discriminating, so that it only calls EntityManager.SaveChanges() when you want to hit the database; otherwise, you could have it do something else, like persist the changes to a local EntitySet file.

You could have it check to see if you're connected before deciding what to do, but that's quite time-consuming, so it's better to keep some flag that reflects your state of connectedness and/or whether you want to hit the database or not with saves and retrieves.



Print Page | Close Window