score:12

Accepted answer

a datacontext can be expensive to create, relative to other things. however if you're done with it and want connections closed asap, this will do that, releasing any cached results from the context as well. remember you're creating it no matter what, in this case you're just letting the garbage collector know there's more free stuff to get rid of.

datacontext is made to be a short use object, use it, get the unit of work done, get out...that's precisely what you're doing with a using.

so the advantages:

  • quicker closed connections
  • free memory from the dispose (cached objects in the content)

downside - more code? but that shouldn't be a deterrent, you're using using properly here.

look here at the microsoft answer: http://social.msdn.microsoft.com/forums/en-us/adodotnetentityframework/thread/2625b105-2cff-45ad-ba29-abdd763f74fe

short version of if you need to use using/.dispose():

the short answer; no, you don't have to, but you should...

score:1

in one particular application, i experienced that, without wrapping the datacontext in using block, the amount of memory usage kept on increasing as the live objects were not released for gc. as in, in below example, if i hold the reference to list<table> object and access entities of q, i create an object graph that is not released for gc.

dbdatacontext db = new dbdatacontext()
var qs = 
    from x in db.tables
    where x.id == someid
    select x;

return qs.tolist();

foreach(q in qs)
{
    process(q);
    // cannot dispose datacontext here as the 2nd iteration 
    // will throw datacontext already disposed exception 
    // while accessing the entity of q in process() function
    //db.dispose();
}

process(table q)
{
    // access entity of q which uses deferred execution
    // if datacontext is already disposed, then datacontext 
    // already disposed exception is thrown
}

given this example, i cannot dispose the datacontext because all the table instances in list variable qs **share the same datacontext. after dispose(), accessing the entity in process(table q) throws a datacontext already disposed exception.

the ugly kluge, for me, was to remove all the entity references for q objects after the foreach loop. the better way is to of course use the using statement.

as far as my experience goes, i would say use the using statement.

score:3

i depends on the complexity of your data layer. if every call is a simple single query, then each call can be wrapped in the using like in your question and that would be fine.

if, on the other hand, your data layer can expect multiple sequential calls from the business layer, the you'd wind up repeatedly creating/disposing the datacontext for each larger sequence of calls. not ideal.

what i've done is to create my data layer object as idisposible. when it's created, the datacontext is created (or really, once the first call to a method is made), and when the data layer object disposes, it closes and disposes the datacontext.

here's what it looks like:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.configuration;

namespace personneldl
{
    public class personneldata : idisposable
    {
        #region datacontext management
        /// <summary>
        /// create common datacontext for all data routines to the db
        /// </summary>
        private personneldbdatacontext _data = null;
        private personneldbdatacontext data
        {
            get
            {
                if (_data == null)
                {
                    _data = new personneldbdatacontext(configurationmanager.connectionstrings["personneldb"].tostring());
                    _data.deferredloadingenabled = false; // no lazy loading
                    //var dlo = new dataloadoptions(); // dataload options go here
                }
                return _data;
            }
        }

        /// <summary>
        /// close out data context
        /// </summary>
        public void dispose()
        {
            if (_data != null)
                _data.dispose();
        }
        #endregion

        #region dl methods
        public person getpersonbyid(string userid)
        {
            return data.persons.firstordefault(p => p.userid.toupper().equals(userid.toupper()));
        }

        public list<person> getpersonsbyidlist(list<string> useridlist)
        {
            var ulist = useridlist.select(u => u.toupper().trim()).tolist();
            return data.persons.where(p => ulist.contains(p.userid.toupper())).tolist();
        }

        // more methods...
        #endregion
    }
}

score:5

well, it's an idisposable, so i guess it's not a bad idea. the folks at msft have said that they made datacontexts as lightweight as possible so that you may create them with reckless abandon, so you're probably not gaining much though.....

score:5

  1. first time datacontext will get object from db.
  2. next time you fire a query to get the same object (same parameters).: you’ll see query in a profiler but your object in datacontext will not be replaced with new one from db !!

not to mention that behind every datacontext is identity map of all objects you are asking from db (you don’t want to keep this around).

entire idea of datacontext is unit of work with optimistic concurrency. use it for short transaction (one submit only) and dispose.

best way to not forget dispose is using ().


Related Query