Today, the desire to use renewable energy as a source of clean and available energy in the grid has increased. Due to the unpredictable behavior of renewable resources, it is necessary to use energy storage resources in the microgrid structure. The power generation source and the storage source in microgrids should be selected in such a way that it has the ability to respond to the maximum demand in the state connected to the grid and operate independently. In this article, the optimal capacity and economic performance of a microgrid based on photovoltaic and battery system have been investigated. In this way, first, using the iterative optimization method, the optimal microgrid capacity has been obtained. Then, the dynamic planning method has been used for optimal microgrid energy management. The simulation results show the accuracy and efficiency of the proposed solutions. The proposed controller, while automatically and dynamically adapting to the solar cell output changes, is capable of responding to external requests, such as price signals or satisfying power system constraints or operator requests. In addition, the results indicate that by using the proposed energy management system, the microgrid system can regain stability during one to two cycles, during the occurrence of PV system radiation changes as well as ESS charge changes. And also, according to the ESS charge changes, the voltage changes should be within the defined permissible range between 0.95 and 1.05 pu, which is the result of the unique efficiency of the proposed energy management system.