Stonehead
Stonehead

Reputation: 376

Entity framework - create context from context

I have a form to fill out document A. Document A has associated documents B and C. A single context is supposed to be used for a single unit of work - such as filling a document A. BUT! I would like to fill B and C while filling A with option to cancel everything. Is it possible, and if it is - how - to create a context from another context instead of the database.

I create a context for document A, and when user starts creating document B, I want a 'subcontext' that save its changes in its 'parent' context.

Can I do that? How? Am I doing something wrong?

Upvotes: 1

Views: 832

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364389

No. You cannot create context for context - at least there is no such built-in functionality so you would have to create your new "subcontext" type and whole its logic completely yourselves.

Simply if you want to work as unit of work use single context. You can use two approaches:

  1. Create document A, B and C with correct references between them and only after that add document A to context and SaveChanges. If user cancels document creation you will simply not add document A to context and never call SaveChanges.
  2. Create document A and add it to context, create document B and add it to context, created document C and add it to context. After that make references between context by setting navigation properties and SaveChanges. If user decides to cancel creation you will dispose current context without ever calling SaveChanges.

Upvotes: 1

Related Questions