Setting the DataContext on an Entity instance after it's retrieved
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 cur开发者_Go百科rently:
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
Although you didn't specify a real reason for it, just a sidenote from MSDN:
In general, a
DataContext
instance is designed to last for one "unit of work" however your application defines that term. ADataContext
is lightweight and is not expensive to create. A typical LINQ to SQL application createsDataContext
instances at method scope or as a member of short-lived classes that represent a logical set of related database operations.
and one more:
Do not try to reuse instances of
DataContext
. EachDataContext
maintains state (including an identity cache) for one particular edit/query session. To obtain new instances based on the current state of the database, use a newDataContext
.
and finally,
... Any instance members are not guaranteed to be thread safe.
But still in some cases semi-persistent solutions could be very helpful. Take a look onto Rick Strachl's article: Linq to SQL DataContext Lifetime Management. There are different approaches of DataContext
management is reviewed in it. On of them - Create a per business object DataContext is exactly what you need.
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.
public class MyDataContext
{
public static MyDataContext Current
{
get
{
MyDataContext context = (MyDataContext)HttpContext.Current.Items["Context"];
if(context == null)
{
context = new MyDataContext();
HttpContext.Current.Items["Context"] = context;
}
return context;
}
}
}
public class MyEntity
{
public MyDataContext DataContext
{
get{ return MyDataContext.Current;}
}
}
In Global.asax you can hook up the event Application_EndRequest
and call MyDataContext.Current.Dispose();
to dispose of the context manually instead of waiting for the GC to do it.
精彩评论