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)?
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.