views:

40

answers:

1

If I detach the context I loose all of the relationships and if I don't I can't save later because the entity's context is disposed...

This is an example of my code

Public Sub Save()
    Using ctx As HMIEntities = New HMIEntities
        ctx.AttachUpdated(Me) //I use this extension method that works fine if I detach in the get method and the entity has no properties as entities
        ctx.SaveChanges()
    End Using
End Sub

Public Shared Function GetByID(ByVal ID As Integer) As Page
    Dim retval As Page
    Using ctx As HMIEntities = New HMIEntities                        
        retval = ctx.PageSet.Include("PageContent").FirstOrDefault(Function(p) p.Slug = ID)            
    End Using
    Return retval
End Function

Is this just going to be impossible??

+1  A: 

Create the context (directly or indirectly) at the start of the request and dispose it at the end of the request. Most people use a DI container with a dedicated HTTP handler for this, but you could do it in Global.asax.cs if you don't want to go that route. Personally, I use MVC, so I do it in a controller factory.

Then, anything which needs a context can get it from the DI container (or via constructor injection) and you'll have a single context for the entirety of each request.

Craig Stuntz
Thanks Craig, I am not familiar with DI containers so I will be asking the Google for more about this approach. If I understand you correctly about using the Global.asax I think I will still have the same problem. A request will need to be made to get the object and another will have to be made to submit the changes, creating a new/different context than the one that was used to get the data. Right? New to EF so excuse me if I'm being dumb.
Mike
The phrases to Google are "Dependency Injection" and "Inversion of Control". **The most important thing** is to have one context per request. That is, for every, individual request, all code which needs to use an ObjectContext will share the same ObjectContext. You can read some discussion about the idea here: http://dotnetslackers.com/articles/ado_net/Managing-Entity-Framework-ObjectContext-lifespan-and-scope-in-n-layered-ASP-NET-applications.aspx For DI, look here: http://www.manning.com/seemann/MEAP_Seemann_01.pdf
Craig Stuntz