Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to handle the DataContext in LINQ to SQL

Tags:

c#

linq-to-sql

I've gotten the go-ahead at work to implement LINQ to SQL for a new module in our ASP.NET app. I forget the best way to handle the DataContext required to retrieve objects; should I create it in every method that makes use of it, or have some kind of Utility class to manage it in a different fashion?

For instance, I have a class that ActiveRecord-style retrieves an entity. Should I be using something like:

using (MyAppDataContext context = new MyAppDataContext()) 
{
    // do stuff here...
}

in each of these methods? I've seen this used frequently in the LINQ tutorials but I've also seen a way where there is a Utilities class that has some method that returns the DataContext (GetContext or similar); I forget if the method was just a wrapper around newing one up or if it did some kind of Singleton-type mechanism.

Which would be the better approach?

like image 937
Wayne Molina Avatar asked Jan 29 '26 13:01

Wayne Molina


1 Answers

Personally, I use something similar to this:

public class MyClass : MyBaseClass
{
     public void GetData()
     {
          using(DbDataContext db = new DbDataContext())
          {
              // DO STUFF
          }
     }

     public void PerformLogicallyAtomicAction()
     {
          using(DbDataContext db = new DbDataContext())
          {
              // DO STUFF
          }
     }
}

Unless there is any need to hold the data context open longer.

Update

To clarify a little bit more on the reasons why I do this:

1) I don't want an object in memory any longer than I need it

Below is the main reason

2) Tracking Change Data causes stale data in some cases (See 2nd comment on OP)

3) Creating the new object takes 0 time (effectively)

4) By creating it every time I need it, I can change specific LINQ options (EG. ObjectTrackingEnabled (which I frequently turn off)

like image 71
Stuart Blackler Avatar answered Feb 01 '26 03:02

Stuart Blackler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!