Quoting from wikipedia: ""In solid state physics, the work function is the minimum energy (usually measured in electron volts) needed to remove an electron from a solid to a point immediately outside the solid surface (or energy needed to move an electron from the Fermi level into vacuum). Here "immediately" means that the final electron position is far from the surface on the atomic scale but still close to the solid on the macroscopic scale. The work function is a characteristic property for any solid face[1] of a substance with a conduction band (whether empty or partly filled). For a metal, the Fermi level is inside the conduction band, indicating that the band is partly filled. For an insulator, the Fermi level lies within the band gap, indicating an empty conduction band; in this case, the minimum energy to remove an electron is about the sum of half the band gap and the work function."
In this particular case wikipedia states "work function is about the sum of half the band gap and the work function". Kind of a recursive definition.
Unfortunately, wikipedia occasionally fails.
Besides, work function is defined for a solid surface, while affinity is defined for an isolated atom. These are completely different things.
Ok, to settle this once and for all.
Work function = Vaccuum energy level - Fermi energy level
As you know the Fermi level is an "average energy of electrons in the solid".
If the Fermi level is 3eV below vacuum level it doesn't mean that an electron state exists that is 3eV below the vacuum level.
This means that if the material is an insulator there will not be any energy states that have energy equal to the Fermi level. Therefore to extract an electron you need to supply energy
= (vacuum energy level) - (valence electron energy)
~= (vacuum energy level) - (Fermi energy) - (1/2) x (energy bandgap)
because usually the Fermi level is approximately in (1/2) x (energy gap) above the top of the valence energy band.
In a metal there are always electrons with energy equal to the Fermi level (actually the highest available energy for electrons . Therefore to extract an electron you need energy
= (vacuum energy level) - (conduction electron energy)
= (Vaccuum energy level) - (Fermi energy level)