Linq to sql insert object after creation in memory

I am creating a booking engine for a car rental location.

I have an l2s reservation object that has Car and Location objects (and subsequent FK fields CarID / LocationID).

In the first step of the booking process, I update the Booking () class. This is passed on in the session to subsequent pages.

As the user navigates through the process, the CarID and LocationID properties are set, however, since the Reservation object has not been saved back to the database, I cannot link, for example, to the Booking.CarModel map.

So I do it explicitly:

Booking.Car = DB.Car.Where(x => x.id == Booking.CarID).Single();

      

and etc.

When it's time to save the booking, it throws out:

An attempt was made to connect or Add an entity that is not new, possibly having been loaded from another DataContext. This is not supported.

So it looks like he thinks the booking object is not new. If I try to exclude the values ​​I set for the definition (Booking.Car = null) it throws another error:

An attempt was made to remove the relationship between the car and the booking. However, one of the foreign keys of the relationship (Booking.CarID) cannot be set to zero.

And now I'm stumped ...


Final decision

What I ended up with (after trying a bunch of different things) was just before the booking was saved, I reload the Car and Location objects from the current context. Not really efficient, but meh.

0


a source to share


1 answer


I'm sure you are having a data processing problem. Are you creating one query? If the answer is yes, the problem is that your objects are associated with different contexts. You will have to decouple them from the context that you used to retrieve them from the database and re-bind them to the context you want to use to store them.



0


a source







All Articles