Reputation: 73
I'm having an issue with my Context lifetimes in an N-Tier application.
An example of a wrapper I am using:
Public Class User
Private _user As DB.User
Private context As New DB.MyContainer
Public Sub New(ByVal UserID As Integer)
_user = context.Users.FirstOrDefault(Function(x) x.Id = UserID)
End Sub
Public Sub Save()
context.SaveChanges()
End Function
This method is causing issues in my UI layer. The data can be updated by the UI layer, and this will still return "stale" data because the context has not been disposed. If in Finalize() i set context.Dispose() then i am unable to access any of the properties of the class.
Should i just call .reload() every time, or should i shorten the context? To shorten it wouldn't i have to detach the entity, then reattach it to the new context when Save() is called?
Upvotes: 0
Views: 128
Reputation: 10566
Please see this article: http://msdn.microsoft.com/en-us/magazine/ee335715.aspx
Create a new ObjectContext instance in a Using statement for each service method so that it is disposed of before the method returns. This step is critical for scalability of your service. It makes sure that database connections are not kept open across service calls and that temporary state used by a particular operation is garbage collected when that operation is over. The Entity Framework automatically caches metadata and other information it needs in the app domain, and ADO.NET pools database connections, so re-creating the context each time is a quick operation.
Upvotes: 1