3

I'm working with a project in ASP.Net using Webforms. I'm using Entity Framework to save data on Microsoft SQL.

My question is:

Is possible to use a Static class to keep the ObjectContext of EF live and put/get entities NOT saved inside the ObjectContext?

I want to create an Object, then added with AddObject on the ObjectContext, But NOT to do the Savechanges. All this in one webform. And then, in other webform, access to the ObjectContext and get the Object when added.

It is this possible?

Community
  • 1
  • 1
Mark Comix
  • 1,776
  • 7
  • 27
  • 44

3 Answers3

2

My rules to using ObjectContext:

  1. Do not use static context.
  2. Do not share context.

You are trying to violate both rules. If you do that your application will have undeterministic behavior. Create new ObjectContext instance for each request. It is the same as openning new connection and starting new transaction in the request instead of sharing one connection and one transaction among all of them.

Further explanation also here. Also check linked question in right column and you will see what type of problems people have just because of violating one or both mentioned rules.

Also in web application it becames even more interesting because ObjectContext is not thread safe.

Community
  • 1
  • 1
Ladislav Mrnka
  • 349,807
  • 56
  • 643
  • 654
  • thanks for the answer. My problem is to keep alive 1 object. I cant go to data base everytime becouse that isnt performance. I dont know what to do – Mark Comix Mar 03 '11 at 18:25
  • What do you mean by keeping alive one object? – Ladislav Mrnka Mar 03 '11 at 18:29
  • My systems is a Webform proyect and is like a wizzard (next, next, cancel, save, etc). Each step on the wizzard is controled by an object called Circuit. I wan to keep on memory the Circuit object for All the Webform. – Mark Comix Mar 03 '11 at 18:32
  • 4
    Then you should use HttpApplicationState or Cache and store Circuit object - not whole ObjectContext. Moreover loading single object from DB each request is usually not performance issue. – Ladislav Mrnka Mar 03 '11 at 18:35
0

You could add it to the application items collection. See this blog post for syntax and such.

http://www.informit.com/articles/article.aspx?p=27315&seqNum=3

asawyer
  • 16,764
  • 8
  • 53
  • 82
0

Generally, you don't want to. An ObjectContext is intended to be a unit of work, alive for a single set of related transactions. In an ASP.NET application, that generally corresponds to a single request.

If you must keep it alive for multiple requests, I wouldn't use either a static class, nor the application context. Instead, I'd recommend using the Cache, and then attaching the callbacks to it that let you ensure all your transactions are committed before it gets evicted, just in case.

Paul
  • 32,974
  • 9
  • 79
  • 112