简体   繁体   中英

LINQ to SQL and open connections

I've always had in my data access layer the following kind of code setup (made up example)

public static class LoadData
{
  private static SomeDataContext db = new SomeDataContext();

  public static void LoadData(DropDownList ddl)
  {
    (from ls in db.MyLookup
    select ls).OrderBy(ls=>ls.theId).ToList()
    .ForEach(ls=>ddl.Items.Add(new ListItem(ls.theText, ls.theValue.ToString())));
  }
}

Is the DataContext "smart" enough to cleanup after itself or should I be wrapping my query with a using statement to make sure connections are closed?

You should most definitely be, at least, using a using block when accessing the database. The Data Context does not automatically open and close the connections for you. You're still responsible for your resources.

You might want to look into using the Unit of Work pattern in case you need to access the database multiple times using a single connection (related data, etc.).

Is the DataContext "smart" enough to cleanup after itself

Data Context's are designed to be used in a small scope; that of a single transaction. As such they won't release any of their resources until you dispose of them and allow the object to go out of scope. Using a single context through your entire application like this will result in the consumption of a significant amount of resources (including a network connection as well as memory (both managed and unmanaged)).

You should instead create a new data context for each LoadData call, and wrap the context in a using to ensure that it's properly disposed after each call.

As noted in comments the data context is also not thread safe, so that is yet another reason not to be re-using the same context across multiple logical transactions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM