views:

48

answers:

2

Hi,

I'm sure most people who use the entity framework sometimes need an entity only for some business operations without it actually ever getting persisted to the database. For example, an online shop checkout wizard where you want to fill the customer and address info, but only persist it once the customer is at the end of the wizard and actually buys the product. There could be other things that I would like to save in the meantime, so I can't have my user object attached to the context, because then it will be saved as well.

Generally I use a unit of work pattern, so my context lifetime is short. The entity would have to exist between different context instances.

These are some of the possibilities I thought of so far:

  • Use detached entities in-memory (session state) and attach them when you want to save them.
  • Just save them anyway and later delete them when they turn out to be unwanted data.
  • Use separate non-EF classes for this and convert to EF when you want to save.

Any other possibilities? Thanks for your insights.

+2  A: 

I would suggest either approach 1 or 3, depending on the rest of your architecture.

If you use EF with POCOs, this really isn't a problem - however, if you use the generated entity classes, you might have another problem: do you map them into POCOs before sending them to the UI layer?
If not, you should change that. Take a look at for example AutoMapper, which will make the mapping process smooth and simple.

The reason I'm pointing you in this direction, is that if you have EF Entities tightly coupled to your business and/or UI layers and later on want to switch EF to something else, you have a lot more work ahead of you than if you have proper mappings.

Tomas Lycken
Yes, I'm using EF4 with POCO's
Jappie
Then I suggest just instantiating your CLR objects, keep them in session state as needed, and attach them to the object context when you need to save them. This will probably be by far the easiest to implement, as you still have to have some intermediate storage between context lifecycles, and you don't force your objectcontexts to keep track of changes they'll never need to know about.
Tomas Lycken
A: 

Option one is probably the best. You can simply create objects of the EF Entities, using their default constructor, change their properties and do whatever you want. They will only be save to the database if you add them to your entity model and call SaveChanges.

MrFox