Access Violation Exception from Entity Framework when invoked from Unit Test RRS feed

  • Question

  • I am using EF4.3, ASP.NET MVC4, Microsoft.VisualStudio.TestTools.UnitTesting.

    Code works fine. I added Unit tests to test Controllers. The Unit tests fails with following exception :

    Access Violation Exception. Attempted to read or write protected  memory. This is often an indication that other memory is corrupt.

    at  ((IObjectContextAdapter)this).ObjectContext.MetadataWorkspace.LoadFromAssembly(typeof(MyBusinessEntity).Assembly);

    I have added [assembly: InternalsVisibleTo("TestProject")]  to my Web project AssemblyInfo.cs

    Any suggestions ?

    Unit test code:

        public void GetEntity() 
            // Arrange 
            MyControllercontroller = new MyController(); 
            // Act 
            var result = controller.GetEntity("737464305") as JsonResult; 
            dynamic data = result.Data; 
            // Assert 
            Assert.AreEqual("0", data.ProcessStatus); 

    Controller action invokes a Stored Procedure using  Entity Framework4.3 DBContext. The result of SP call is mapped to a Complex Type.  The DBContext code for the SP call is :

    public virtual ObjectResult<MyEntity> MYSP(string inparam) 
            var inparamParameter = inparam != null ? 
                new ObjectParameter("inparam", inparam) : 
                new ObjectParameter("inparam", typeof(string)); 
            return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<MyEntity>("MYSP", inparamParameter ); 

    In general code works fine. However,  Access Violation Error is thrown when Controller action is tested using Unit Test. in line ((IObjectContextAdapter)this).ObjectContext.MetadataWorkspace.LoadFromAssembly(typeof(MyEntity).Assembly);

    Monday, August 20, 2012 7:30 PM


  • I found the problem. iF ProxyCreationEnabled property of dbContext is set to false, then Unit tests on Controllers or BL methods which inturn invoke SP through Entity Framework are failing with AccessViolation Exception.

    • Marked as answer by Mindspring Tuesday, August 21, 2012 3:53 PM
    Tuesday, August 21, 2012 3:53 PM