0

Considering that I use code like (with or without using (considering that using(??) may dispose context)):

IQueryable<Konsultanci> listaKonsultantow;
using (var context = new EntityBazaCRM(Settings.sqlDataConnectionDetailsCRM)) {
       listaKonsultantow = from k in context.Konsultancis
                                                   select k;
}

Can I somehow extract context that was used from Konsultanci object later on so I don't have to store context on top of the class?

 foreach (Konsultanci test in listaKonsultantow) {
       // get context here? 
 }
MadBoy
  • 10,213
  • 18
  • 88
  • 146
  • I load those objects from SQL Server. This is continuation of http://stackoverflow.com/questions/9086722/can-entity-framework-context-be-reused-all-the-time-in-code and http://stackoverflow.com/questions/9083709/the-relationship-between-the-two-objects-cannot-be-defined-because-they-are-atta After lots of errors I defined `private readonly EntityBazaCRM context = new EntityBazaCRM(Settings.sqlDataConnectionDetailsCRM);` on top of the class and it solved my problems. But I would rather get the Context from object I;m working with rather then have one defined in the class. – MadBoy Jan 31 '12 at 21:50

2 Answers2

1

Since you dispose your context at the end of the using block you should not even try.

Albin Sunnanbo
  • 44,354
  • 8
  • 64
  • 104
  • What if I would not use `using`? But `EntityBazaCRM context = new EntityBazaCRM(Settings.sqlDataConnectionDetailsCRM);` ? – MadBoy Jan 31 '12 at 21:48
  • @MadBoy, when do you plan to dispose your context then? – Albin Sunnanbo Jan 31 '12 at 21:57
  • On GUI close? I'm trying to fix problems that arrise like the one I described here (http://stackoverflow.com/questions/9083709/the-relationship-between-the-two-objects-cannot-be-defined-because-they-are-atta). After fighting with it for 5 hours putting context on top and reusing it solved the problem. So right now I'm trying to find optimal approach. Unless you've got a way to solve the problem differently then I can get back to using `using`. – MadBoy Jan 31 '12 at 22:03
1

Separating the context out as a concern will lead down the path of many design patterns that will interest you. You should definitely look into repositories and dependency injection (unity is MS's DI Container which helps to manage dependencies such as the data context issue you are having). If these topics are beyond the scope of your project, then re-typing your using statement is probably not a concern.

Travis J
  • 77,009
  • 39
  • 185
  • 250