You can prevent Margret's death at the very beginning, if you're quick enough. Also, according to UESP, "It is not necessary to complete all objectives to advance the quest to the final stage. Upon completion of any task AFTER discovering Margret's status as a spy, the final scene will trigger the next time you enter the Shrine of Talos." If you already go to Nepo's house or the treasury house and the NPCs inside have become aggressive - maybe try using a calming spell on them, exiting the house, fast travelling away and back to Markarth? Not sure if it will work, but it's always worth a try.
In any case, you cannot prevent the deaths of the guy who attacks Margret, the guy you meet at the shrine of Talos and Betrid SIlver-Blood (it's scripted, she dies even if there's no one to killher).
As for NPC deaths during the quests that follows Forsworn Conspiracy:
Spoiler 1) Try timing the escape so that it happens during the night (most citizens should be in their homes around 1-4 a.m.). Also, once you're out of the mine, run straight for the city gates - all your co-prisoners should follow you immediately.
OR
2) Klill Madanach and escape on your own. Other prisoners, however, are then scripted to die.