Fix issue 597 -- entity manager is properly removed even if close operation fails + unit test.