SebastianR
SebastianR

Reputation: 2233

Lifetime of DbContext in Entity Framework Core 2.0 and UWP

I'm currently moving my UWP app from sqlite-net to Entity Framework Core 2.0 with Sqlite as a database provider. What I'm wondering is what lifetime DbContext objects should have.

I've seen tutorials for Entity Framework and WPF which suggest that you should keep the instance of DbContext alive for the lifetime of a details view. This allows you to change the model and save the changes when the user presses a button by calling SaveAsync() or to cancel the changes by simply closing the view. My app would greatly benefit from this feature. (Currently all changes are immediately stored in the database, which is not optimal.)

The issue that I see with keeping DbContext for a longer time is that in UWP the app can be suspended at any time and the memory might be wiped. I assume that EF will lose all changes done on the model when the app restarts. So theoretically it is possible that the user changes the model in a details views, switches to another task and does some that causes heavy memory usage, which leads to the termination of my app. As the changes were only stored in memory they would be lost.

So how should one approach the lifetime of DbContext in UWP? I've considered these ways:

  1. A transient lifetime, which would mean that I can't use the save/cancel mechanism
  2. keep DBContext alive for as long as a view is open and accept the possible, but probably unlikely loss of unsaved data
  3. keep DBContext alive for as long as a view is open and somehow serialize all changes to the models when the app is suspended. This would probably require complex logic to restore the exact state of the model the user left off with.

Upvotes: 1

Views: 532

Answers (1)

Martin Zikmund
Martin Zikmund

Reputation: 39102

Overall when building UWP apps it is recommended to save data as soon as possible to avoid such a risk of losing user data. This holds true not only for Entity Framework but also for other data storage options.

The problem is with data that are temporary (draft) only as in your case is the work-in-progress form. In this case, you probably don't want to save the data into the database. Instead, you should store the data in a temporary file or in local app settings. After the app is reopened, you may check if there is some temporary data saved and restore the previous state of the application. You can go even further by restoring the whole Frame navigation stack. There is a nice helper class SuspensionManager which you can use for this purpose.

For more recommendations see the documentation and UX guidelines.

Upvotes: 1

Related Questions