Skip to content

Commit

Permalink
fix: reduce ef dbcontext lifetime to short as possible (#21)
Browse files Browse the repository at this point in the history
No more long lived dbContext.
  • Loading branch information
fuzzzerd authored Oct 11, 2023
1 parent dbb721f commit fe1ab49
Showing 1 changed file with 14 additions and 12 deletions.
26 changes: 14 additions & 12 deletions SharpFM.App/ViewModels/MainWindowViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@ public partial class MainWindowViewModel : INotifyPropertyChanged
{
private readonly ILogger _logger;

public readonly ClipDbContext _context;

public event PropertyChangedEventHandler? PropertyChanged;

private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
Expand All @@ -30,14 +28,14 @@ public MainWindowViewModel(ILogger logger)
{
_logger = logger;

_context = new ClipDbContext();
_context.Database.EnsureCreated();
using var clipContext = new ClipDbContext();
clipContext.Database.EnsureCreated();

_logger.LogInformation($"Database path: {_context.DbPath}.");
_logger.LogInformation($"Database path: {clipContext.DbPath}.");

FileMakerClips = new ObservableCollection<ClipViewModel>();

foreach (var clip in _context.Clips)
foreach (var clip in clipContext.Clips)
{
FileMakerClips.Add(new ClipViewModel(
new FileMakerClip(
Expand All @@ -53,7 +51,9 @@ public MainWindowViewModel(ILogger logger)

public void SaveToDb()
{
var dbClips = _context.Clips.ToList();
using var clipContext = new ClipDbContext();

var dbClips = clipContext.Clips.ToList();

foreach (var clip in FileMakerClips)
{
Expand All @@ -66,7 +66,7 @@ public void SaveToDb()
}
else
{
_context.Clips.Add(new Clip()
clipContext.Clips.Add(new Clip()
{
ClipName = clip.Name,
ClipType = clip.ClipType,
Expand All @@ -75,19 +75,21 @@ public void SaveToDb()
}
}

_context.SaveChanges();
clipContext.SaveChanges();
}

public void ClearDb()
{
var clips = _context.Clips.ToList();
using var clipContext = new ClipDbContext();

var clips = clipContext.Clips.ToList();

foreach (var clip in clips)
{
_context.Clips.Remove(clip);
clipContext.Clips.Remove(clip);
}

_context.SaveChanges();
clipContext.SaveChanges();
}

public void ExitApplication()
Expand Down

0 comments on commit fe1ab49

Please sign in to comment.