We investigate the baryon fraction in dark matter haloes formed in non-radiative gas-dynamical simulations of the LambdaCDM cosmogony. By combining a realisation of the Millennium Simulation (Springel et al.) with a simulation of a smaller volume focussing on dwarf haloes, our study spans five decades in halo mass, from 10^10 Msun/h to 10^15 Msun/h. We find that the baryon fraction within the halo virial radius is typically 90% of the cosmic mean, with an rms scatter of 6%, independently of redshift and of halo mass down to the smallest resolved haloes. Our results show that, contrary to the proposal of Mo et al. (2005), pre-virialisation gravitational heating is unable to prevent the collapse of gas within galactic and proto-galactic haloes, and confirm the need for non-gravitational feedback in order to reduce the efficiency of gas cooling and star formation in dwarf galaxy haloes. Simulations including a simple photoheating model (where a gas temperature floor of T_{floor} = 2x10^4 K is imposed from z=11) confirm earlier suggestions that photoheating can only prevent the collapse of baryons in systems with virial temperatures T_{200} < ~2.2 T_{floor} ~ 4.4x10^4 K (corresponding to a virial mass of M_{200} ~ 10^10 Msun/h and a circular velocity of V_{200} ~ 35 km/s). Photoheating may thus help regulate the formation of dwarf spheroidals and other galaxies at the extreme faint-end of the luminosity function, but it cannot, on its own, reconcile the abundance of sub-L* galaxies with the vast number of dwarf haloes expected in the LambdaCDM cosmogony. The lack of evolution or mass dependence seen in the baryon fraction augurs well for X-ray cluster studies that assume a universal and non-evolving baryon fraction to place constraints on cosmological parameters.