I overtook a WPF project where entity framework is used. The person before me used a single global DbContext. After some reading it became clear that this is a bad practice because of several reasons. Now my job is to refactor the project to use a DbContextFactory and create new DbContext per unit-of-work.
One method i.e. SaveSales calls another method IncreaseReceiptNumber. Inside IncreaseReceiptNumber an entry is added to a table and SaveChanges is called. Now inside SaveSales i create a DbContext with using (var clientDB = dbContextFactory.Create() {}.
My question is, in a case like this should I pass the DbContext from SaveSales to IncreaseReceiptNumber or should IncreaseReceiptNumber create it's own DbContext? Or in a more general sense, should every method create a new DbContext or can a DbContext passed on via parameter if it belongs to the unit-of-work?
IMO, there is no single answer to this question. You must decide for each case whether or not the overhead of multiple connections is warranted (overhead is small with pooling, but exists), if the sharing of a single DbContext provides extra benefits (entities already attached), and if sharing makes things more difficult (you're calling the method in a loop, and risk "connection already open" errors) . These factors have to be weighed on a case-by-case basis. For what it's worth, I have done all of these things...use the right tool for the job, as they say.
Related
I'm using MVC .Net. Usually I always use something like below to create one instance whenever I need to query the DB:
using (EntitiesContext ctx = new EntitiesContext())
{
....
}
Then I see lots of sample codes that always have one instance of DBContext in the controller, use it whenever needed, and Dispose it when the controller is Disposed.
My question is: which one is the right way to use it? Any advantage/disadvantage? Maybe, is there any performance difference?
Thanks
Using a context by controller instance has multiple advantages :
It's scoped to the controller, therefore if you need it multiple times you allocate only one instance
EntityFramework use local caching, then if you query multiple times over the same DbSet with the same parameters, it will match those entities in cache instead of querying the database
If you use the repository pattern, it's a good practice to share your context accross repositories. That way, each repository is able to see what as been done by other repositories if you manipulate multiple repository in the same controller scope
From the Getting Started with ASP.NET 5 and Entity Framework 6 , you can read :
Context should be resolved once per scope to ensure performance and ensure reliable operation of Entity Framework.
See a related SO post that deeply explain why it's better to use this approach.
This question already has answers here:
Why re-initiate the DbContext when using the Entity Framework?
(2 answers)
Closed 7 years ago.
I'm working on a c# project which uses Entity Framework 6 for MySql. for Adding objects to the dbContext I use the following approach:
public void Add(User item)
{
using (var ctx = new DbContext())
{
ctx.Users.Add(item);
ctx.SaveChanges();
}
}
Now I need to know if it is ok to have one DbContext object for instance:
private DbContext _ctx = new DbContext();
and change the Add method to
public void Add(User item)
{
_ctx.Users.Add(item);
_ctx.SaveChanges();
}
And then to have another method to dispose the DbContext object and call it when the application is quitting.
Is it a good approach? what are the cons and pros of this approach?
thanks in advanced.
Consider the pros and cons of having a DbContext as a class member:
Pros:
You save one line of code and two braces
Cons:
It is not thread safe. One thread could try to read or write data generated from another thread that may not be in a correct state.
The context will grow in size as objects are added, increasing memory usage.
Someone has to dispose of the containing class.
For web apps it won't matter since each request creates its own objects (unless you cache them in Application or Session)
DbContext is designed to be used per database request. Per MSDN:
A DbContext instance represents a combination of the Unit Of Work and Repository patterns such that it can be used to query from a database and group together changes that will then be written back to the store as a unit.
All in all, the benefit is clearly not worth the cost.
You don't want to do this in web apps. Why? Multiple reasons:
You risk locking all of the requests on a single thread
Sessions can bleed into each other, ending up with one user changing another user's data
While it may seem spinning up multiple contexts affects performance (and makes your coding more involved), underneath the hood things are handled quite nicely.
How about a windows app? Depends. If the app is always connected, it may work in some instances. Certainly makes it easier than spinning up. But, the downside is it consumes resources on the data side whether any work is being done, or not.
In general, I prefer a more optimistic, disconnected system. If that is not the system you need (need, not want), then you might consider it. But, as a rule, I would not have a single instance for an app.
For a class that I have, I am noticing I basically have to use the following scenario for each function within a class. Is this inefficient? Is there a better to utilize the DataContext object?
using (var context = new SomeDataContext(getConnectionString))
{
//linq query here
}
It is designed to be used the way you mentioned. You should create a new context each and every time you do something on the database. As #Dan points out, creating a Context is extremely fast and efficient.
That's a correct and proper way to do it because it guarantees that you are disposing of the connection by putting it in a using clause. Instantiating a DBContext is not prohibitively expensive either.
With that said, you are creating one DBContext every time you query your database and disposing of it immediately, so you are not taking advantage of Caching and other niceties offered by the DbContext class.
One "cheap and dirty" way to create only one DBContext per request would be to instantiate one on Application_BeginRequest and store it in the HttpContext.Items collection (basically in a temp Cache) and disposing of it on Application_EndRequest. Each class in your project would then get the current DBContext from the HttpContext.Items cache and use it. The connection will be properly disposed since Application_EndRequest always fires regardless of errors.
A better alternative is to use a Dependency Injection framework (Structure Map, Ninject, etc.) You can google for tutorials on how to do this. SO has several questions that would help you if you are interested in implementing it.
Personal note: Don't worry about any of that stuff unless you noticee that your app is performing too slow to be acceptable. Your current approach is fine.
If I am using a SqlConnection, apparently the best practice is to dispose of it ASAP, and let the connection pooling handle the details. Should I follow the same pattern when I am using System.Data.Linq.DataContext?
Should I create my context once and pass it along to my methods, or should I get the connection string from my config file and create the contexts multiple times and save on passing the parameters?
Edit: A useful link about identity maps: Architecting LINQ To SQL Applications, part 7
You should keep a data context around only as long as necessary to perform an operation.
The reason for this is that it uses something called an Identity Map so that every time you select say customer 1 you get the same object back. This means it is holding lots of references and will consume more and more memory over time and these results will become increasingly stale.
In the case of a web app it is common to create one per request and the DataContext class is optimised for quick creation.
I'm implementing a DAL using the Entity Framework. We have some DAL classes (I call them repositories) instantiating or receiving a context by parameter every time a method is called. I don't like that kind of behavior; I'm not documented about this issue but my common sense says me that context's instantiation consumes too much system resources. So:
Is context's instantiation expensive?
If you've answered "yes" to 1, how would you tackle this problem from a design viewpoint?
If you've answered "yes" to 1, how would you implement the solution in C#?
Which approach do you recommend to implement a DAL for a web application?
my common sense says me that context's instantiation consumes too much system resources
Common sense is nearly useless when it comes to optimization.
What exactly in the constructor of context do you suppose will be problematic? Have you read the source for it yet?
1) Is context's instantiation expensive?
Relative to what? Compared to the amount of time required to establish a database connection? Compared to the time it takes to perform your site's DNS lookup? Compared to the amount of time a browser might spend rendering your page?
The vast liklihood is that context's instantiation is not particularly time consuming compared to the time required to actually retrieve data across the network.
2) If you've answered "yes" to 1, how would you tackle this problem from a design viewpoint?
Use a UnitOfWork abstraction. Each UnitOfWork should contain a single entity context. If this is a web app you should have one UnitOfWork per request.
Context lifetime management is a crucial when using ORMs. The entity framework context in keeps information about loaded entities for lazy loading and change tracking purposes and its memory footprint may grow very quickly. If you don't dispose your context you will essentially have a memory leak.
However, you are correct that keeping the context lifetime too short is not ideal since you would probably like to make use of change tracking.
using (var context = new DataContext())
{
context.Products.Add(product);
context.SaveChanges();
}
The above example shows disposes the context too quickly to take advantage of the change tracking goodies.
For Web applications you should use context per request.
For Win Form applications you can dispose of your context when you move from one form to another.