This is a really good topic and one which probably does not have a simple answer.
The first thing I would suggest is for you to study melodies you like or find memorable. Dissect them--what harmonies are suggested by them, how quickly do those harmonies change, how does the rhythm help the melody, how are dissonant intervals used to spice up the melody and generate tension? There are countless questions you can ask about every melody, and they are all worthwhile questions. Really study the melodies you enjoy and get as much information from them as possible.
My second point of advice would be to sing. While at the piano, sing the notes that you are playing. Like another user suggested, if you know poetry, now would be a good time to use it, using the words as your lyrics. Start with a single note, playing it and singing it, and then try to let your voice, rather than your fingers, guide you to the next note. I did this about a month ago. I was wanting to set a poem by Mallarme to music, and I had a good idea for the first half of the first stanza, but my fingers couldn't quite find what to do next. So I started singing and without any effort found a smooth countermelody.
If you already know where the sonata is going harmonically, this singing method is easier. Simply play a progression and sing to it. Use poetry, famous speeches, monologues from film or theatre, even the words of other songs to guide you rhythmically and expressively. This method might take a little getting used to, but you might find that you have a natural inclination to singing melody that you might not quite have in your fingers.