Dispose Entity DbContext in WinForms

entity-framework entity-framework-6 winforms


In Windows Forms application, when form starts, it loads data from database. It first goes to Persistence Data layer and creates new DBContext.

public DataEntities DBContext = new DataEntities();

After this it loads data.

I dispose DBContext on form close event. The reason for that is that I use Local property of DBContext to query data. So it queries memory data after loading and not database which is good (fast). The other thing is that only user who starts program has access to his own data (and not data of other users). So there is very little chance anyone can modify his data (only his deputy).

So, DBContext is not disposed until form is closed.

Note 1: this is form for entering data. It is not Main form. On Main Form I will dispose it immidiatelly as Main form is just for viewing data.

Note 2: application will be used in local network and number of users is around 40.

Note 3: I use entity framework 6.1.3

After loading data at start, in sql profiler I noticed sql command is called:

exec sp_reset_connection

My question is: Can I use this approach and dispose DBContext when form closes (on form closing event)?

6/17/2016 2:34:17 PM

Accepted Answer

Sure. This is known as a connected scenario, i.e. the context stays "connected" (mind the quotes) to the database and you save the same entities as you grabbed from the database.

In a rich client application like a Windows Forms application this is a common pattern for relatively short-lived edit dialog windows. And that's exactly what you're doing here.

The context doesn't actually keep an open connection to the database. It closes the connection after each database interaction, hence the Sql Profiler logging.

One thing to consider. Even though there's little chance that users edit the same data simultaneously, it may be recommended to introduce optimistic concurrency control. EF makes this relatively easy.

6/17/2016 6:58:34 PM

Popular Answer

When your DbContext has a long live time then here are some consideration (Connected entities):

  • Each retrieved entity from the SQL Server will be loaded into memory in the First level cache (RAM USAGE).

  • If the data changed from other DbContext you might get some concurrency issues.

  • If your SQL Server TRANSACTION ISOLATION LEVEL is READ UNCOMMITTED then you might get a dirty read.

  • If you a lot of entities which are loaded in the DbContext(Thousands) then the applicaiton will be generally slower and maybe you will get a performance issues when you try to change an entity beacuse the EF has to Track them all.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow