Mike
Mike

Reputation: 5529

How can I handle an entity with other entities as children over different application layers

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??

Upvotes: 0

Views: 86

Answers (1)

Craig Stuntz
Craig Stuntz

Reputation: 126587

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.

Upvotes: 1

Related Questions