title: Entity Framework Core Unique Index testing
body: <p>I have a model class:</p>
  
  <pre class="lang-cs prettyprint-override"><code>public class Work
  {
      public long Id { get; set; }
  
      [Required]
      public string Name { get; set; }
  }
  </code></pre>
  
  <p>I want this <code>Work.Name</code> will be unique, so I define the <code>DbContext</code>:</p>
  
  <pre class="lang-cs prettyprint-override"><code>public class MyDbContext : DbContext
  {
      public MyDbContext () : base() { }
      public MyDbContext (DbContextOptions&lt;MyDbContext &gt; options) : base(options) { }
  
      protected override void OnModelCreating(ModelBuilder modelBuilder)
      {
          modelBuilder.Entity&lt;Work&gt;(entity =&gt;
              entity.HasIndex(e =&gt; e.Name).IsUnique()
          );
      }
      public DbSet&lt;Work&gt; Works { get; set; }
  }
  </code></pre>
  
  <p>And I want to test this, so I have a test like this:</p>
  
  <pre class="lang-cs prettyprint-override"><code>[Fact]
  public void Post_InsertDuplicateWork_ShouldThrowException()
  {
      var work = new Work
      {
          Name = "Test Work"
      };
  
      using (var context = new MyDbContext (options))
      {
          context.Works.Add(work);
          context.SaveChanges();
      }
  
      using (var context = new MyDbContext (options))
      {
          context.Works.Add(work);
          context.SaveChanges();
      }
  
      using (var context = new MyDbContext (options))
      {
           Assert.Equal(1, context.Works.Count());
      }
  }
  </code></pre>
  
  <p>( The <code>option</code> object contains settings for <code>InMemoryDatabase</code>)</p>
  
  <p>I don't really know what to check, but the test failed <strong>in the <code>Assert</code></strong>, not in the second <code>SaveChanges()</code>. The database (the <code>context</code>) contains two objects with the same <code>Name</code>.</p>
  
  <p>I went over all the relevant questions, but I did not see anyone answering what I was asking.</p>