2

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.

user3530012
  • 720
  • 2
  • 20
  • 37
  • What kind of project? – SLaks Aug 13 '15 at 17:19
  • 6
    Related: http://stackoverflow.com/questions/7647912/why-re-initiate-the-dbcontext-when-using-the-entity-framework and http://stackoverflow.com/questions/13551100/when-should-i-create-a-new-dbcontext – D Stanley Aug 13 '15 at 17:20

2 Answers2

4

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.

D Stanley
  • 149,601
  • 11
  • 178
  • 240
2

You don't want to do this in web apps. Why? Multiple reasons:

  1. You risk locking all of the requests on a single thread
  2. 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.

Gregory A Beamer
  • 16,870
  • 3
  • 25
  • 32