score:12
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
- first time datacontext will get object from db.
- 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 ().
Source: stackoverflow.com
Related Query
- In LINQ-SQL, wrap the DataContext is an using statement - pros cons
- Determine the source DataContext for a Linq to Sql query
- SQL issue- statement returning the same even though trying to sort the fielld using where - nested query - convert to LINQ
- What is the easiest way to find the LINQ statement for a SQL statement
- Why didn't the LINQ designers stick with using the way sql is written today?
- Equivalent of SQL Between Statement Using Linq or a Lambda expression
- Left outer join using LINQ -- understanding the code
- LINQ to Entities using the SQL LIKE operator
- How can I write the following code more elegantly using LINQ query syntax?
- What are the prerequisites for using SQL and LINQ with my winforms application in C#?
- How to code the partial extensions that Linq to SQL autogenerates?
- Does LINQ to SQL support the t-sql "in" statement
- BestPractice: Pros and Cons for using AutoMapper or LINQ (LINQ to Objects) for mapping between a Domain Model and a Presentation Model
- How to go through 2 vectors in paralle using the same linq statement
- How to know which Linq statement produced the SQL on hand during runtime?
- How to work around the fact that Linq to SQL is using separate SQL DELETE statements for each item in DeleteAllOnSubmit
- Linq to SQL intellisense has no knowledge of tables within the datacontext object
- Is a full list returned first and then filtered when using linq to sql to filter data from a database or just the filtered list?
- dynamically varied number of conditions in the 'where' statement using LINQ
- Two way binding in WPF trough LINQ to SQL for the property of a ListItem of a ListBox using a DataTemplate
- If you have a LINQ statement using the Select() method, is there a way to get a value from the next record?
- Using the equivalent to the SQL IN function with LINQ with a collection
- Is there a secret to using LINQ to SQL to add records when the object has relationships?
- In a table a column datatype is varchar, retrieve only those values of the column which are number / numeric using linq to sql
- Updating LINQ to SQL but the query i have is from a join? Can't update using query that uses a join?
- LINQ operators versus LINQ methods: limitations, pros / cons of one over the other?
- How to write this code using the Linq Extension Method-Syntax?
- How can I check the number of calls to the database in LINQ query when using .NET Core and Code First?
- LINQ to SQL - Using TransactionScope for SELECT statement - is call to Complete() necessary?
- How to create a LINQ To SQL datacontext for large DB using SQLMetal when it generates a 12MB DataContext.cs file?
More Query from same tag
- C# EF Linq syntax query with multiple conditions and in clause
- Extending Telerik client template column and getting the values passed through
- C# compilation error with LINQ and dynamic inheritance
- how to bind data to gridcontrol in WPF
- Linq select query, how to append results to object of a class
- linq to xml - get childrem of those nodes with a certain attribute
- Issue with Lambda to sort a list
- Anyone knows any Linq to XQuery implementation?
- How do I keep the lastest entry of an item from a database
- DataGridView & Linq
- C#: ToArray performance
- c# Razor Pages Select Tag Helper
- C# Multiple Parameter From Single Expression
- LINQ to Entities does not recognize the method
- Issue with LINQ group by with count
- Joining two tables and selecting a relating value from the first
- Associated indexes of two list
- Filter entityframework core with conditionals in linq
- Return full results linq grouping query
- Insert using linq templates not returning the id - MySQL
- LINQ Select and Convert Entites to ViewModels
- SQL to LINQ (to implement LEFT JOIN)
- How can I return an IOrderedEnumerable from a Collection based on OrderBy "property"
- How to replace a particular string in c# using regex or linq
- Convert IAsyncEnumerable to List
- LINQ where query on a JToken
- Linq to group by two fields and average
- Send Email multiple attachments from LINQ list
- Convert nullable int to int in linq query return anonymous type
- Entity Framework (4.2) HasRequired results in unexpected LEFT OUTER JOIN