I’m trying to find a way to have the DataContext available from within Entities.
I want to do something like this:
partial public class MyEntity
public DataContext as MyDataContext
private sub OnLoaded()
Me.DataContext = <the context that retrieved this instance>
end sub
end class
First, can something like this be done?
Second, assuming that I’m not going to use this entity with any other DataContext, is there any dangers or gotchas in doing such a thing?
This is the way I do it currently:
partial public class MyDataContext
public function GetMyEntity(byval id as integer) as MyEntity
dim o = MyEntities.SingleOrDefault(function(e) e.id = id)
if o isnot nothing then o.DataContext = Me
return o
end function
end class
You could use a singleton pattern on the DataContext, but you will need some kind of lifetime management on it, as it is not good to keep it around to long. (request ends dispose it maybe)
Example in C#, but I hope you can understand it.
In Global.asax you can hook up the event
Application_EndRequestand callMyDataContext.Current.Dispose();to dispose of the context manually instead of waiting for the GC to do it.