在我的WPF MVVM应用程序中,我希望对于我的Entity Framework实体类所做的更改能够自动持久化到数据库。我已经有一些关于实现这个功能的想法,但似乎没有一个是最优的。
以下是我目前的(非最优)想法:
所以,我的问题是:在您的经验或其他方面,如何最好地解决这个问题?
提前感谢。
以下是我目前的(非最优)想法:
Use a
DispatcherTimer
to save changes every interval:DispatcherTimer timer = new DispatcherTimer(); timer.Interval = TimeSpan.FromSeconds(1); timer.Tick += (sender, args) => Repository.SaveChanges(); timer.Start();
Save changes in the program's
OnExit()
method.protected override void OnExit(ExitEventArgs e) { Repository.SaveChanges(); base.OnExit(e); }
Save changes every time
OnPropertyChanged()
is called on one of myEntities
:protected virtual void OnPropertyChanged(string propertyName) { Repository.SaveChanges(); }
A combination of 2 & 3; save the data after counting an arbitrary number of property changes and also save in
OnExit()
to catch any changes that didn't reach the change limit:const int limit = 5; int changes = 0; protected virtual void OnPropertyChanged(string propertyName) { if (++changes == limit) { Repository.SaveChanges(); changes = 0; } }
所以,我的问题是:在您的经验或其他方面,如何最好地解决这个问题?
提前感谢。