Firstly it's used to get the right pH for DNA extraction, but Tris is preffered over other buffers because Tris interacts with the lipopolysaccharides present on the outer membrane which helps to permeabilize the membrane. This effect is enhanced with the addition of EDTA (ethylenediaminetetraacetic acid), which is a chelating agent that captures metal ions (like Ca2+).
When membranes are busted by TRIS, there is no compartmentalization in the solution anymore. MgCl2 is then used because it binds to DNA and thus protects it against DNase proteins that are now (because of lack of membranes) in direct contact with your DNA.
The binding of MgCl2 to DNA denies access of DNase to the DNA, and your DNA will not be broken down.