The error is caused by a foreign key ID (as opposed to a reference) which cannot be resolved. In your case, you have a LocationInRole that references a Location with an ID of 0. There are multiple Locations with this ID.
The Locations have not yet been assigned an ID because they have not yet been saved to the database which is when the ID is generated. In your second example, the Locations are saved before their IDs are accessed which is why this works.
You will not be able to rely on the Location IDs to define the relationships if you want to SaveChanges only later.
Swap the following line…
LocationId = locations[i].Id
…for this…
Location = locations[i]
The relationships will then be based on object references which are not dependent on the LocationIDs.