I can get an erection and maintain it but cannot ejaculate when having sex. I can ejaculate when masturbating most of the time?

Ejaculation problems. Masterbation is a much more intense sexual stimulant due to one's ability to control the intensity of stimulation. Talk to your partner about this issue and remind them that it is not their fault. Talk about other possible positions, stimulation of other parts (scrotum, rectum, neck, ears, etc) to intensify your sexual experience. Performance anxiety may be an issue that a therapist can help with.
See a sex therapist. It really depends on your age.If you are young in your "sex life" it will probably straighten out. If this a lifetime problem with all your partners you probably need some help. There are no pills for a chronic problem. A competent sex therapist can help. Check the sstar website for good therapists in your area.
Stimulation is a key. So is letting go, allowing yourself to be engaged. It's easy to get caught up in making sure you stay hard long enough and she is satisfied. Ultimately you have to reach that "stimulation threshold" where it's enough arousal to make you climax, then you have to give yourself permission and let it go, really turn off your head and just FEEL!