title: How to Run Xunit in Parallel without Collision in DbContext - Primary Key?
body: <p>I am creating Xunit tests, with in-memory database. The tests execute correctly if run separately. However if run in parallel, they collide due to primary key issue in dbcontext. </p>
  
  <p>What is best option to resolve this?</p>
  
  <ol>
  <li>Does Xunit have teardown capability? Heard xunit does not
  support this. </li>
  <li>Should I just run tests sequentially? </li>
  <li>Should go ahead and use different key Ids?</li>
  </ol>
  
  <p>Trying to research xunit documentation, just started learning .net programming.</p>
  
  <p><strong>Error:</strong></p>
  
  <pre><code>"System.ArgumentException : An item with the same key has already been added. Key: 2"
  </code></pre>
  
  <p><strong>Code:</strong></p>
  
  <p>2 is primary key, used twice</p>
  
  <pre><code>public class ProductAppServiceTest
  {
      public TestContext context;
      public IMapper mapper;
      public ProductAppServiceTest()
      {
          var options = new DbContextOptionsBuilder&lt;TestContext&gt;()
              .UseInMemoryDatabase(databaseName: "TestDatabase")
              .Options;
          context = new TestContext(options);
  
          ApplicationServicesMappingProfile applicationServicesMappingProfile = new ApplicationServicesMappingProfile();
          var config = new MapperConfiguration(cfg =&gt;
          {
              cfg.AddProfile(applicationServicesMappingProfile);
          });
          mapper = config.CreateMapper();
      }
  
      [Fact]
      public async Task Get_ProductById_Are_Equal()
      {
          context.Product.Add(new Product { ProductId = 2, ProductCode = "123", ProductName = "ABC" });
          context.SaveChanges();
  
          var ProductRepository = new ProductRepository(context);
          var ProductAppService = new ProductAppService(ProductRepository, mapper);
          var ProductDto = await ProductAppService.GetProductById(2);
  
          Assert.Equal("123", ProductDto.ProductCode);
      }
  
      [Fact]
      public async Task Get_ProductPrice_Are_Equal()
      {
          context.Product.Add(new Product { ProductId = 2, ProductCode = "123", ProductName = "ABC" });
          context.SaveChanges();
  
          var ProductRepository = new ProductRepository(context);
          var ProductAppService = new ProductAppService(ProductRepository, mapper);
          var ProductDto = await ProductAppService.GetProductById(2);
          //Goes into Enum table to validate price is 5
          Assert.Equal("5", ProductDto.Price);
      }
  </code></pre>