linq data context abstraction
I'm finding myself writing this line for every query:
using ( MyDataModel thisDataContext = new MyDataModel() )
{
linq query
}
Is there开发者_如何转开发 a better way to declare a data context?
Thanks.
you can create a DataService
class that represent your DataContext
e.g.:
public class BaseDataService:IDisposable
{
protected MyDataModel thisDataContext = null;
public BaseDataService(string connection)
{
this.thisDataContext = new MyDataModel (connection);
}
public void Dispose()
{
this.thisDataContext.Connection.Close();
this.thisDataContext.Dispose();
}
}
then create methods that satisfy your needs e.g.:
public class YourEntityDataService:BaseDataService
{
public YourEntityDataService(string connection):base(connection)
{
}
public YourEntity GetYourEntity()
{
//LINQ CODE
}
public void SaveYourEntity (YourEntity entityToSave)
{
//LINQ CODE
}
}
We actually put our data context object on the current thread as Thread Static object. Doing this does away with us having to pass the context object around to each method that needs it.
We have an n-tier architecture, and when our middle tier is called from a client, we just new up a context object and put it on the thread. Then, any method that needs to make a database call just pulls the context object off the thread. So, there are very few places in our middle-tier code where we are actually creating a context object. In fact, just one place, if I recall correctly.
Even with this method, our context objects don't live all that long (which is a good thing).
精彩评论