C# 只向DbContext添加一次数据

C# 只向DbContext添加一次数据,c#,asp.net-core,entity-framework-core,xunit,xunit.net,C#,Asp.net Core,Entity Framework Core,Xunit,Xunit.net,我创建了一个XUnit fixture来定义EF核心上下文初始数据: public class ServiceProviderFixture : IDisposable { public IServiceProvider Provider { get; private set; } public ServiceProviderFixture() { IServiceCollection services = new ServiceCollection(); servi

我创建了一个XUnit fixture来定义EF核心上下文初始数据:

public class ServiceProviderFixture : IDisposable {

  public IServiceProvider Provider { get; private set; }

  public ServiceProviderFixture() {
    IServiceCollection services = new ServiceCollection();
    services.AddDbContext<Context>(x => { x.UseInMemoryDatabase("Database"); });
    Provider = services.BuildServiceProvider();
    BuildContext();
  }

  private void BuildContext() { 
    Context context = Provider.GetService<Context>();
    context.Countries.Add(new Country { Code = "fr", Name = "France" });
    context.SaveChanges();
  }

  public void Dispose() { } 

} 
我相信BuildContext()在同一上下文中每个TestClass被调用一次


我该如何解决这个问题呢?

只要在构建上下文中检查是否有数据,如果没有,就创建它,否则什么也不做。或者,您可以在测试完成后清理创建的数据

  private void BuildContext() { 
    Context context = Provider.GetService<Context>();
    if(!context.Countries.Any())
    {
        context.Countries.Add(new Country { Code = "fr", Name = "France" });
        context.SaveChanges();
    }
  }
private void BuildContext(){
Context=Provider.GetService();
如果(!context.Countries.Any())
{
添加(新国家{Code=“fr”,Name=“France”});
SaveChanges();
}
}

因为您总是以相同的方式命名内存中的数据库,所以您总是再次获得相同的数据库

您必须为每个测试用例使用不同的名称(例如,
Guid.NewGuid().ToString()

services.AddDbContext(x=>
x、 UseInMemoryDatabase($“数据库{Guid.NewGuid()}”)
);
An item with the same key has already been added. Key: fr
The following constructor parameters did not have matching fixture data:
ServiceProviderFixture fixture)
  private void BuildContext() { 
    Context context = Provider.GetService<Context>();
    if(!context.Countries.Any())
    {
        context.Countries.Add(new Country { Code = "fr", Name = "France" });
        context.SaveChanges();
    }
  }
services.AddDbContext<Context>(x => 
    x.UseInMemoryDatabase($"Database{Guid.NewGuid()}")
);