Remove the iPad from the Magic Keyboard - and carefully/gently clean the smart connector contacts on both the iPad and keyboard with a soft pencil eraser (a drafting-film eraser is ideal). Ensure that the contacts on both iPad and keyboard are dirt and dust free - and all debris from the eraser have been removed - before reconnecting the two.
This support page may be helpful:
If you can't connect your iPad to your Magic Keyboard, Smart Keyboard, or Smart Keyboard Folio - Apple Support
If problems persist, you would be best advised to visit the Genius Bar at your local Apple Store or Apple Authorised Service Provider (AASP) - where the technicians will be able to test and assess your iPad and Magic Keyboard:
Genius Bar Reservation and Apple Support Options - Apple