samedi 25 juin 2022

How scared should I be of creating new DbContexts?

I often has a situation like this. I have to create a bunch of lines/row to show the user for each row in some database table. And if the user then clicks on the row it should update in the database.

One way of handling this is scetched below (It might not compile, but I think you get the idea).

This creates and closes a DbContext everytime the user interacts.

public class MainViewModel
{
   public ICollection<RowViewModel> Items 
   {
      get
      {
        var allRows = new List<RowViewModel>();
        using var dbContext = CreateDbContext();
        foreach(var item in dbContext.items) 
        {
           var row = new RowViewModel(item);
           allRows.add(row);
        }
        return allRows;
      }
   }
}

public class RowViewModel
{
  private Item _row;
  public RowViewModel(Item row)
  {
    _row = row;
  }
  public void OnDoubleClick()
  {
     using var dbContext = CreateDbContext();
     dbContext.Items.Attach(_row);
     _row.SomeValue += 1;
     dbContext.SaveChanges();
  }
}

An alternative would be to keep the DbContext alive in MainViewModel and then pass it around.

public class MainViewModel : IDisposable
{
   private MyDbContext _dbContext;

   public MainViewModel()
   {
     _dbContext = CreateDbContext();
   }

   public void Dispose()
   {
     _dbContext?.Dispose();
   }


   public ICollection<RowViewModel> Items 
   {
      get
      {
        var allRows = new List<RowViewModel>();
        foreach(var item in _dbContext.items) 
        {
           var row = new RowViewModel(item, _dbContext);
           allRows.add(row);
        }
        return allRows;
      }
   }
}

public class RowViewModel
{
  private Item _row;
  private MyDbContext _dbContext;
  public RowViewModel(Item row, MyDbContext dbContext)
  {
    _row = row;
    _dbContext = dbContext;
  }
  public void OnDoubleClick()
  {
     _row.SomeValue += 1;
     _dbContext.SaveChanges();
  }
}

I'm torn between the two designs.

Any thoughts/preferences?

Yours
/peter

Aucun commentaire:

Enregistrer un commentaire