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

sorry i missed this before: please add the apache copyright header to this file.  you can copy it from the top of the other ones, just fix up the year.