0

What's the difference between creating a new DbContext for each transaction:

using (var context = new MyDbContext()) { /* transaction */ } 

and using one across the whole application

var context = MyDbContext.Singleton; */ transaction */ 

1 Answer 1

2

One (the first) is the correct way to do it.

The other is the incorrect way to do it.

Entity Framework is designed to have short lived contexts. It does no memory management or cleanup at runtime, and just continues to grow and use memory the longer it exists. It is designed to be disposed of after every use. Your code is broken if you use it the second way.

If you're developing a web app, it's even worse. The second method can cause data corruption, because the context gets shared across all users, and the state will be corrupted by multiple users trying to hammer on it at the same time.

Sign up to request clarification or add additional context in comments.

2 Comments

"Entity Framework is designed to have short lived contexts. It does not memory management or cleanup" - can you elaborate?
@CalebJares - Not sure what there is to elaborate about. It does no cleanup of it's memory at runtime. It's caches grow until you run out of memory. It is designed to be disposed of after each use.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.