I’m new to the Entity Framework and have a question about ObjectContext
lifecycle in a ‘database-first’ WinForm application.
For the sake of illustration, let’s say I am creating a register of animal species.
On the left of the form I have a list of animal species (cow, pig, dog etc. – I think these are genus rather than species, but never mind!).
On the right of the form I have textboxes, comboboxes etc. to display and allow editing of the selected species’ properties.
When the user selects a species on the left I use:
var species = context.Single(x => x.id == speciesID);
then bind the various controls on the right to species
.
Some of these properties such as habitat are selected from a combobox (populated from the database when the form loads. I'm using surrogate keys in the database) which means I think I need to keep the same context for the life of the form.
I think there are two problems with this:
The user could make changes to many different species (several hundred exist) during the life of the context making it become bloated.
Ideally I would like to prompt the user when selecting a new species if they wish to save changes to the current one (if dirty) before changing. How then do I discard changes – how do I make the context forget it ever saw the object?
An alternative would be to use a new context each time the user selects a new species, but this would mean repopulating several comboboxes each time so that they are created on the same context and can be bound to.
Am I missing something?
Many Thanks