I'm building a booking engine for a car hire place.
I have a Booking l2s object, which has a Car and Location objects (and subsequent FK CarID / LocationID fields).
During the first step of the booking process, I new up a Booking() class. This is passed along in a session to the subsequent pages.
As the user proceeds through the process, the CarID, and LocationID properties are set, however because the Booking object has not been persisted back to the database, I cannot reference Booking.Car.CarModel for example.
So what I am doing is setting it explicitly:
Booking.Car = DB.Car.Where(x => x.id == Booking.CarID).Single();
etc.
When it comes time to save the Booking, it throws a:
An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. This is not supported.
So it would seem it's thinking the Booking entity is not new. If I try and null out the values I've explicity set (Booking.Car = null), it throws another error:
An attempt was made to remove a relationship between a Car and a Booking. However, one of the relationship's foreign keys (Booking.CarID) cannot be set to null.
And now I'm stumped...
Final Solution
What I ended up doing (after trying a bunch of different things) was just prior to saving the Booking, I reload the Car and Location objects from the current context. Not exactly efficient, but meh.