title: Mvvm Light and Entity Framework Core best practices
body: <p>I'm creating a new UWP application using Mvvm Light and Entity Framework Core. I'm new to these 2 technologies.</p>
  
  <p>I create my model : the <strong>Article</strong> class is a simple ObservableObject with 3 properties : <em>Id</em>, <em>Référence</em> and <em>Désignation</em>.</p>
  
  <p>My DbContext is the following :</p>
  
  <pre><code>public class UniversalTest1Context : DbContext
  {
      public DbSet&lt;Article&gt; Articles { get; set; }
  
      protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
      {
          optionsBuilder.UseSqlite("Filename=UniversalTest1.db");
      }
  
  }
  </code></pre>
  
  <p>I'm looking for the best way to manage the DbContext and my different views.</p>
  
  <p>Is it better to create one DbContext for the whole application ? <em>I don't really like that idea</em>.</p>
  
  <p>Do I have to create a DbContext in each ViewModel ? <em>I like this  more</em>.<br>
  When the user double tap an item in the article list view, I navigate to the article detail view and pass the article to the view model associated to the article detail view. But this already existing article is not related to the DbContext of the Article detail view model.</p>
  
  <p>Is it possible to instantiate the DbContext only when needed ? <em>My prefered option</em>.<br>
  For this, I pass the article from the list view model to the detail view model. And then, when the user clicks save I execute something like this :</p>
  
  <pre><code>using (var db = new UniversalTest1Context())
  {
      db.Articles.Add(article);
      await db.SaveChangesAsync();
  }
  </code></pre>
  
  <p>Of course, this works for new articles (insert), but not for existing ones (update).</p>
  
  <p>I have difficulties making up my mind here. </p>
  
  <p>Many thanks in advance,
  Julien</p>