To prevent the cheese from getting grainy, make sure that the pasta is cooked al dente before adding the cheese sauce. You should also stir the cheese sauce in slowly, so that the pasta doesn't cool down too much.