Observations show that Coronal Mass Ejections (CMEs) are associated with twisted magnetic flux configurations. Conventionally, CMEs are modeled by shearing and twisting the footpoints of a certain distribution of magnetic flux at the solar surface and letting it evolve at the surface. Of course, the surface velocity and magnetic field patterns should ultimately be obtained from realistic simulations of the solar convection zone where the field is generated by dynamo action. Therefore, a unified treatment of the convection zone and the CMEs is needed. Numerical simulations of turbulent dynamos show that the amplification of magnetic fields can be catastrophically quenched at magnetic Reynolds numbers typical of the interior of the Sun. A strong flux of magnetic helicity leaving the dynamo domain can alleviate this quenching. In this sense, a realistic (magnetic) boundary condition is an important ingredient of a successful solar dynamo model. Using a two-layer model developed in this thesis, we combine a dynamo-active region with a magnetically inert but highly conducting upper layer which models the solar corona. In four steps we improve this setup from a forced to a convectively driven dynamo and from an isothermal to a polytropic stratified corona. The simulations show magnetic fields that emerge at the surface of the dynamo region and are ejected into the coronal part of the domain. Their morphological form allows us to associate these events with CMEs. Magnetic helicity is found to change sign in the corona to become consistent with recent helicity measurements in the solar wind. Our convection-driven dynamo model with a coronal envelope has a solar-like differential rotation with radial (spoke-like) contours of constant rotation rate, together with a solar-like meridional circulation and a near-surface shear layer. The spoke-like rotation profile is due to latitudinal entropy gradient which violates the Taylor--Proudman balance through the baroclinic term. We find mean magnetic fields that migrate equatorward in models both with and without the coronal layer. One remarkable result is that the dynamo action benefits substantially from the presence of a corona becoming stronger and more realistic. The two-layer model represents a new approach to describe the generation of coronal mass ejections in a self-consistent manner. On the other hand, it has important implications for solar dynamo models as it admits many magnetic features observed in the Sun.