user42
user42

Reputation: 347

How to best utilize DBContext with a Web API application

I have a Web API that uses an Entity Framework DBContext to perform CRUD operations. My question is the following:

Initially, I used a static instance of my DBContext. However, with this format, any changes to the database tables do not display when I query the dataset again; the data is stale.

As a temporary fix, at the beginning of all my public class functions, I am creating a new DBContext object and calling that object to get data from the database. This is not the best idea for many reasons. But the data is no longer stale when I use this technique.

How do I utilize a DBContext appropriately so that multiple users will always see the current database data from a request? Should I put the DBContext as a field in my class and instantiate it in the constructor for the class? In that case, should each class have its own DBContext object?

Is there a best practice for using a DBContext appropriately? I am concerned about stale data and inaccurate results being pushed to my users.

Upvotes: 0

Views: 1604

Answers (2)

Tim B
Tim B

Reputation: 2368

It should also be noted that Entity Framework caches data. If you make changes to cached data directly in the database, Entity Framework will not see those changes until you create a new DbContext, or tell the underlying ObjectContext to Refresh.

Upvotes: 1

tia
tia

Reputation: 9708

DbContext is not thread-safe, so making it static is not a good thing for server code. The overhead of creating a DbContext is low so I do not see why we have to avoid making it instance variable.

Upvotes: 3

Related Questions