Should Entity Framework Context be Put into Using Statement? - c#

The Entity Framework context object implements a Dispose() method which "Releases the resources used by the object context". What does it do really? Could it be a bad thing to always put it into a using {} statement? I've seen it being used both with and without the using statement.
I'm specifically going to use the EF context from within a WCF service method, create the context, do some linq and return the answer.
EDIT: Seems that I'm not the only one wondering about this. Another question is what's really happening inside the Dispose() method. Some say it closes connections, and some articles says not. What's the deal?

If you create a context, you must dispose it later. If you should use the using statement depends on the life time of the context.
If you create the context in a method and use it only within this method, you should really use the using statement because it gives you the exception handling without any additional code.
If you use the context for a longer period - that is the life time is not bound by the execution time of a method - you cannot use the using statement and you have to call Dispose() yourself and take care that you always call it.
What does Dispose()do for an object context?
I did not look at the code, but at least I exspect it to close the database connection with its underlying sockets or whatever resources the transport mechanism used.

Per Progamming Entity Framework: "You can either explicitly dispose the ObjectContext or wait for the garbage collector to do the job."
So in short, while the using statement isn't required, it's best practice if you know you're done using the ObjectContext since the resource is freed up immediately instead of waiting for garbage collection.

Since you don't know when the garbage collector disposes an item, it's always good to wrap up objects that implement IDisposable in a using-block if you know when you're done with it.

EF5 and before version
using { ...
// connecction open here.
...
context.Blogs.Add(blog);
context.SaveChanges(); // query etc now opens and immediately closes
...
context.Blogs.Add(blog);
context.SaveChanges(); // query etc now opens and immediately closes
}
EF6 and after version
using {
// connecction open here.
...
context.Blogs.Add(blog);
context.SaveChanges();
// The underlying store connection remains open for the next operation
...
context.Blogs.Add(blog);
context.SaveChanges();
// The underlying store connection is still open
} // The context is disposed – so now the underlying store connection is closed
Reference: http://msdn.microsoft.com/en-us/data/dn456849#open5

Always, if you instantiate a class that implements IDisposable, then you are responsible for calling Dispose on it. In all but one case, this means a using block.

When you dispose, the ObjectContext disposes other owned objects.
Including things like the EntityConnection which wraps the actual database connection, i.e. generally a SqlConnection.
So 'if' the SqlConnection is open it will be closed when you dispose the ObjectContext.

I realy tested this thing for both ADO.net and EF v.6 and watched connections in SQL table
select * from sys.dm_exec_connections
Methods to be tested looked like this:
1) ADO.net with using
using(var Connection = new SqlConnection(conString))
{
using (var command = new SqlCommand(queryString, Connection))
{
Connection.Open();
command.ExecuteNonQueryReader();
throw new Exception() // Connections were closed after unit-test had been
//finished. Expected behaviour
}
}
2) ADO.net withour using
var Connection = new SqlConnection(conString);
using (var command = new SqlCommand(queryString, Connection))
{
Connection.Open();
command.ExecuteNonQueryReader();
throw new Exception() // Connections were NOT closed after unit-test had been finished
finished. I closed them manually via SQL. Expected behaviour
}
1) EF with using.
using (var ctx = new TestDBContext())
{
ctx.Items.Add(item);
ctx.SaveChanges();
throw new Exception() // Connections were closed, as expected.
}
2) EF without using
var ctx = new TestDBContext();
ctx.Items.Add(item);
ctx.SaveChanges();
throw new Exception() // Connections WERE successfully closed, as NOT expected.
I don't know why is it so, but EF automatically closed connections. Also All the patterns of repository and UnitOfWork which use EF don't use using. It's very strange for me, because DBContext is Disposable type, but it's a fact.
Maybe in Microsoft they did something new for handling?

I have noticed (although in only one application) that the explicit disposal was causing thread abort exceptions in mscorlib which are caught before the application code, but at least in my case resulting in a noticeable performance hit. Haven't done any significant research on the issue, but probably something worth consideration if you are doing this. Just watch your DEBUG output to see if you are getting the same result.

If Dispose closes connection to DB it is a bad idea to call it.
For example in ADO.NET connections are in connection pool and never be closed before timeout or application pool stop.

Related

C# SQL Connection try/catch vs using vs try/catch w/ using

I am the third generation to work on a system within my organization and of course there are differences in programming styles. I was wondering what the correct way of connecting to a database is as there are two different styles being used within the system. So whats the "correct" way?
Method 1:
try
{
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
using (SqlCommand command = new SqlCommand("StoredProcedure", con))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("foo", bar));
}
using (SqlDataReader reader = command.ExecuteReader())
{
//do stuff
}
}
}
catch (Exception ex)
{
//do stuff
}
Method 2:
// Variables
SqlCommand loComm;
SqlConnection loConn = null;
SqlDataReader loDR;
try
{
// Init command
loComm = new SqlCommand("foo");
loComm.CommandType = CommandType.StoredProcedure;
loComm.Parameters.AddWithValue("foo", bar);
// Init conn
loConn = new SqlConnection(String);
loConn.Open();
loComm.Connection = loConn;
// Run command
loDR = loComm.ExecuteReader();
//do stuff
}
catch (Exception ex)
{
//do stuff
}
While both methods work I am not sure which one is the most appropriate to use. Is there a reason to use one over the other? The second method is cleaner and easier to understand to me, but it doesn't automatically run the iDispose() function when it is finished.
Edit: My question is different then the one suggested, because one approach uses the "using" statement while the other doesn't. So my question is directly related to whether or not to utilize the "using" statements when making a database connection.
Thanks, for all the responses.
Method 2 is simply incorrect and should be repaired.
When completed, you will be left with IDisposable instances that have not been disposed. Most likely, this will play havoc with the connection management that goes on behind the scenes with SqlConnection, especially if this code gets thrashed a lot before GC decides to step in.
If an instance is IDisposable, then it needs to be Disposed of, preferably in the smallest scope possible. Using using will ensure that this happens, even if the code malfunctions and exceptions are thrown.
A using statement:
using(var disposableInstance = new SomeDisposableClass())
{
//use your disposable instance
}
is (give or take a few minor details) syntactic sugar for:
var disposableInstance = new SomeDisposableClass();
try
{
//use your disposable instance
}
finally
{
//this will definitely run, even if there are exceptions in the try block
disposableInstance.Dispose();
}
Even if something goes wrong in the try block, you can be assured that the finally block will execute, thereby ensuring that your disposables are disposed, no matter what happens.
In the first example, if there is an exception thrown, the objects wrapped in the using blocks will be properly closed and disposed.
In the second, you will manually need to dispose of your objects.
One other thing worth mentioning is that if you were planning on disposing of your objects only when an exception is thrown, you will have objects that are not disposed of, so you would need to implement a try..catch..finally and dispose the objects within the finally block.
The first is the better option.
The first one will close the connection if an exception is thrown.
The second one won't, so I'd say go with the first choice.
What the using block does is to warranty that the object Dispose method will always be invoked, no matter if an exception is thrown or not.
Dispose is a method used to clean up resources. In the case of a DB connection, the connection is released, which is really important.
So, the correct way in this case is using the using pattern.
The object included between the using parents mus be IDisposable whic means that it has a Dispose method that should be invoked when the object is no longer needed. If you don't invoke dispose, it will be disposde at any indeterminate time, when the garbage collector destroys the object. That's undesirable in case like a DB connection that must be closed as soon as possible.
The equivalen of usin is a try finally, which includes a call to Dispose within the finally block.
Reading here, it says:
As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement. The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and cannot be modified or reassigned. The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.
That sounds like the correct way is method 1.

Entity Framework, DBContext and using() + async?

There is a thing that's been bugging me for a long time about Entity Framework.
Last year I wrote a big application for a client using EF. And during the development everything worked great.
We shipped the system in august. But after some weeks I started to see weird memory leaks on the production-server. My ASP.NET MVC 4 process was taking up all the resources of the machine after a couple of days running (8 GB). This was not good. I search around on the net and saw that you should surround all your EF queries and operations in a using() block so that the context can be disposed.
In a day I refactored all my code to use using() and this solved my problems, since then the process sits on a steady memory usage.
The reason I didn't surround my queries in the first place however is that I started my first controllers and repositories from Microsofts own scaffolds included in Visual Studio, these did not surround it's queries with using, instead it had the DbContext as an instance variable of the controller itself.
First of all: if it's really important to dispose of the context (something that wouldn't be weird, the dbconnection needs to be closed and so on), Microsoft maybe should have this in all their examples!
Now, I have started working on a new big project with all my learnings in the back of my head and I've been trying out the new features of .NET 4.5 and EF 6 async and await. EF 6.0 has all these async methods (e.g SaveChangesAsync, ToListAsync, and so on).
public Task<tblLanguage> Post(tblLanguage language)
{
using (var langRepo = new TblLanguageRepository(new Entities()))
{
return langRepo.Add(RequestOrganizationTypeEnum, language);
}
}
In class TblLanguageRepo:
public async Task<tblLanguage> Add(OrganizationTypeEnum requestOrganizationTypeEnum, tblLanguage language)
{
...
await Context.SaveChangesAsync();
return langaugeDb;
}
However, when I now surround my statements in a using() block I get the exception, DbContext was disposed, before the query has been able to return. This is expected behaviour. The query runs async and the using block is finished ahead of the query. But how should I dispose of my context in a proper way while using the async and await functions of ef 6??
Please point me in the right direction.
Is using() needed in EF 6? Why do Microsoft's own examples never feature that? How do you use async features and dispose of your context properly?
Your code:
public Task<tblLanguage> Post(tblLanguage language)
{
using (var langRepo = new TblLanguageRepository(new Entities()))
{
return langRepo.Add(RequestOrganizationTypeEnum, language);
}
}
is disposing the repository before returning a Task. If you make the code async:
public async Task<tblLanguage> Post(tblLanguage language)
{
using (var langRepo = new TblLanguageRepository(new Entities()))
{
return await langRepo.Add(RequestOrganizationTypeEnum, language);
}
}
then it will dispose the repository just before the Task completes. What actually happens is when you hit the await, the method returns an incomplete Task (note that the using block is still "active" at this point). Then, when the langRepo.Add task completes, the Post method resumes executing and disposes the langRepo. When the Post method completes, the returned Task is completed.
For more information, see my async intro.
I would go for the 'one DbContext per request' way, and reuse the DbContext within the request. As all tasks should be completed at the end of the request anyway, you can safely dispose it again.
See i.e.: One DbContext per request in ASP.NET MVC (without IOC container)
Some other advantages:
some entities might already be materialized in the DbContext from
previous queries, saving some extra queries.
you don't have all those extra using statements cluttering your code.
If you are using proper n-tiered programming patters, your controller should never even know that a database request is being made. That should all happen in your service layer.
There are a couple of ways to do this. One is to create 2 constructors per class, one that creates a context and one that accepts an already existing context. This way, you can pass the context around if you're already in the service layer, or create a new one if it's the controller/model calling the service layer.
The other is to create an internal overload of each method and accept the context there.
But, yes, you should be wrapping these in a using.
In theory, the garbage collection SHOULD clean these up without wrapping them, but I don't entirely trust the GC.
I agree with #Dirk Boer that the best way to manage DbContext lifetime is with an IoC container that disposes of the context when the http request completes. However if that is not an option, you could also do something like this:
var dbContext = new MyDbContext();
var results = await dbContext.Set<MyEntity>.ToArrayAsync();
dbContext.Dispose();
The using statement is just syntactic sugar for disposing of an object at the end of a code block. You can achieve the same effect without a using block by simply calling .Dispose yourself.
Come to think of it, you shouldn't get object disposed exceptions if you use the await keyword within the using block:
public async Task<tblLanguage> Post(tblLanguage language)
{
using (var langRepo = new TblLanguageRepository(new Entities()))
{
var returnValue = langRepo.Add(RequestOrganizationTypeEnum, language);
await langRepo.SaveChangesAsync();
return returnValue;
}
}
If you want to keep your method synchronous but you want to save to DB asynchronously, don't use the using statement. Like #danludwig said, it is just a syntactic sugar. You can call the SaveChangesAsync() method and then dispose the context after the task is completed. One way to do it is this:
//Save asynchronously then dispose the context after
context.SaveChangesAsync().ContinueWith(c => context.Dispose());
Take note that the lambda you pass to ContinueWith() will also be executed asynchronously.
IMHO, it's again an issue caused by usage of lazy-loading. After you disposed your context, you can't lazy-load a property anymore because disposing the context closes the underlying connection to the database server.
If you do have lazy-loading activated and the exception occurs after the using scope, then please see https://stackoverflow.com/a/21406579/870604

Is Disposing of Entity Framework context object required

We are using entity framework for communication with database in our WCF service methods, recently we run the code review tool on our service code. As usual we got many review proposals by tool and many review comments were suggesting to dispose the Entity Framework context object. So, my question is if I use a Entity Framework context object within a method and once I come out of the method, GC doesn't clean up the context object ? do we need to explicitly dispose context object ?
Simply: DbContext implements IDisposable, therefore you should dispose of it, manually, as soon as you're done with it.
You don't need to dispose of it, because the GC will collect it eventually, but the GC isn't deterministic: you never know when "eventually" will be. Until it's disposed, it will be holding resources that aren't in use - for example, it may still have an open database connection. Those resources aren't freed until the GC runs, unless you dispose manually. Depending on specific details you may find that you have unnecessarily blocked network resources, file accesses, and you will certainly be keeping more memory reserved than you need to.
There's a further potential hit, too: when you dispose of an object manually, the GC doesn't typically need to call the Finalizer on that object (if there is one). If you leave the GC to automatically dispose of an object with a Finalizer, it'll place the object in a Finalizer Queue - and will automatically promote the object to the next GC generation. This means that an object with a finalizer will always hang around for orders of magnitude longer than it needs to before being GCed (as successive GC generations are collected less frequently). DBContext would likely fall into this category as the underlying database connection will be unmanaged code.
(Useful reference.)
I think the best approach is coding it within a using statement
using(var cx = new DbContext())
{
//your stuff here
}
so it got automaitaclly disposed
In general if something implements IDisposable it's a Good Idea(TM) to explicitly dispose of it when you're through. This is especially true if you do not own the implementation of said object; you should treat it as a black box in this case. Additionally, even if it were not necessarily "required" to dispose of it now, it may be in the future.
Therefore, IMHO the question of whether you "need to" explicitly dispose of the object is irrelevant. If it is asking to be disposed of - by virtue of implementing IDisposable - it should be disposed of.
The recommended thing to do with a DBContext is to not dispose of it at all (it is the exception to the rule in most cases), even though is a disposable object.
An example of the issue, ths first example is taking a call and evaluation it in the using statement, while the second evaluates it after. (first ons runs, second one throws error The operation cannot be completed because the DbContext has been disposed.)
List<Test> listT;
using (Model1 db = new Model1())
{
listT = db.Tests.ToList(); //ToList Evaluates
}
foreach (var a in listT)
{
Console.WriteLine(a.value);
}
IEnumerable<Test> listT1;
using (Model1 db = new Model1())
{
listT1 = db.Tests;
}
foreach (var a in listT1) //foreach evaluates (but at wrong time)
{
Console.WriteLine(a.value);
}
The same issue happens in
IEnumerable<Test> listT1;
Model1 db = new Model1();
listT1 = db.Tests;
db.Dispose();
foreach (var a in listT1) //foreach evaluates (but at wrong time)
{
Console.WriteLine(a.value);
}
Aslong as you dont open the connection manually you are safe by just using
IEnumerable<Test> listT1;
Model1 db = new Model1();
listT1 = db.Tests;
foreach (var a in listT1) //foreach evaluates (but at wrong time)
{
Console.WriteLine(a.value);
}
and never disposing. as it will take care of itself under most circumstances, as thats what it's designed to do.
Now should you open up a connection by force then the context wont close it automatically when the transfer is done, as it don't know when and then you must/should dispose the object or close the connection and keep the object undisclosed.
Extra midnight reading:
http://blog.jongallant.com/2012/10/do-i-have-to-call-dispose-on-dbcontext.html#.U6WdzrGEeTw
https://msdn.microsoft.com/en-us/data/jj729737.aspx
There is no need to explicitly dispose DbContext.
This is an old hold over from pre-DbContext tools. DbContext is managed code and optimistically maintains database connections on its own. Why sledgehammer it? Whats the hurry? Why not just let the garbage collector decide the best time to clean up when the machine is idle or in need of memory? Also refer to this post: https://blog.jongallant.com/2012/10/do-i-have-to-call-dispose-on-dbcontext/
By not worrying about having to dispose will simplify and optimize your code. Typically I might inherit from a database "helper" class to where I use a getter to either return an already existing DbContext instance, or instantiates a new instance. .
public class DataTools
{
private AppContext _context;
protected AppContext Context => _context ?? (_context = new AppContext());
}
pubic class YourApp : DataTools
{
public void DoLotsOfThings()
{
var = Context.SomeTable.Where(s => s.....);
var stuff = GetSomeThing();
foreach(){}
}
Public string GetSomething()
{
return Context.AnotherTable.First(s => s....).Value;
}
}

How to limit TranscactionScope to given DataBaseContext in C#?

I would like to be 100% that when I use such pattern
using (var scope = new TransactionScope())
{
db1.Foo.InsertOnSubmit(new Foo()); // just an example
db1.SubmitChanges();
scope.Commit();
}
the transaction scope will only refer to db1 not db2 (db1 and db2 are DataBaseContext objects). So how to limit scope to db1 only?
Thank you in advance.
The strength of TransactionScope is that it automatically catches everything within it, down the call stack (unless another TransactionScope with RequiresNew or Supress). If this is not what you want, you should use another mechanism for the transaction handling.
One way is to open SqlConnection and call BeginTransaction to get a transaction, then use that DB connection when creating your data context. (Maybe you'll have to set the Transaction propery on the data context, I'm not sure).
In the example you have given above, the use of a TransactionScope is totally redundant. There is only one function call that actually modifies the database: SubmitChanges and it always creates its own transaction if there isn't already one existing. The reason is that when you're doing several operations SubmitChanges should either succeed in them all or fail all. If you're only after transactional integrity for a single SubmitChanges call for a single data context, then you can just drop the TransactionScope.
As far as I know, what you are after is exactly what you have written, the compiler will ensure that transaction is completed when you commit.
If you use:
using (var scope = new TransactionScope(TransactionScopeOption.RequiresNew))
{
db1.Foo.InsertOnSubmit(new Foo()); // just an example
db1.SubmitChanges();
scope.Commit();
}
You can be sure a new transcation is created for this scope, so everyting you do inside the scope has its own transaction, and will never use any existing ambient transactions.

Close a thread against a mysql database in c#

What is the proper way of closing a tread after running a query against a MySql database from a windows form in C#?
Is a simple open close enough like this?
conn.Open();
//querycode
conn.Close():
Try to use:
using(MySqlConnection conn = new MySqlConnection(connString))
{
conn.Open();
} // conn is automatically closed and disposed at the end of the using block
it is okay the way you are doing it, you can also wrap connection object into using block like this:
using (var con = new MySqlConnection(/*connection string*/))
{
con.Open();
//do stuff
// con.Close(); //don't need this it will be closed automatically*
}
(*see)
No, the code in your question is not good enough. If your query throws an exception you won't Close() it in a timely manner and it will be left hanging until the garbage collector notices it.
You need to enclose the object in a using block as shown by others or at a bare minimum encase it in a try/finally structure.
Classes that use resources that you need to clean up afterwards usually implement the IDisposable interface. This means it provides a function called Dispose() that can be used to free resources.
For disposable objects, you can use the using statement:
using ( SomeDisposableClass c = new SomeDisposableClass() ) {
// ... your code here
} // c.Dispose() automatically called here, freeing up resources
If the class is properly coded, it should free any resources -- be it a database connection, an opened file handle, etc -- in its Dispose() function.
This means that the MySQL probably disconnects from the database in Dispose(), so you probably don't need to explicitly call c.Close() -- but always check the documentation to be sure.

Categories