Exporting generated electricity by on-site renewable energy systems from buildings to the grid is only slightly profitable in many countries. Therefore, it is required to investigate the benefits of sharing generated energy in a microgrid within a community of buildings. Exploiting the benefits of peer-to-peer energy exchange between prosumers in a community can make the best use of the on-site generation while reducing their bills. This study elaborates the potential of energy management to minimize the electricity cost of a community consisted of multiple buildings and connected to a microgrid. To implement this, an energy management system is designed based on non-linear economic model predictive control and successive linear programming for sharing the on-site surplus generated electricity between the buildings in the community. Four buildings are simulated and studied as an example of a small community. These buildings are dissimilar in their age, thermal mass, insulation, heating system and on-site renewable energy systems. It is shown that considering the community of buildings as a single entity, the novel model predictive control can be efficiently used for minimizing the energy cost of the community that has various sources of energy generation, conversion and storage, including significant non-linear interactions. Three different scenarios of the energy management system for the studied community are investigated, and the results indicate that the annual electricity energy cost for single buildings can be reduced by 3.0% to 87.9%, depending on the building and its systems, and by 5.4% to 7.7% on the community level.