我正在尝试向 DbContext 添加迁移,
add-migration initial -verbose
我得到错误
No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.
我的解决方案中有两个 .netcore 类库项目和 netcore 单元测试项目
- 域(Poco类)
- 存储库(.Net Core 2.1,EntitiFrameworkCore 2.1.4)
- 存储库测试
这是我的 DataContext 类
public class DataContext:DbContext
{
public DataContext(DbContextOptions<DataContext> option) : base(option)
{
}
public DataContext()
{
}
public DbSet<User> User { get; set; }
public DbSet<Cart> Cart { get; set; }
public DbSet<CatalogItem> CatalogItem { get; set; }
}
带有 DbContextOptions 对象的构造函数已经存在。
可能是什么问题?
这是测试项目中的一个类。
public class CustomerRepositoryIntegrationTest
{
[Fact]
public void should_add_customer()
{
//Arrange
var option = new DbContextOptionsBuilder<DataContext>()
.UseSqlServer(@"Data Source=(LocalDb)\MSSQLLocalDB;Database=ecommerce;Integrated Security=SSPI").Options;
//Act
using (DataContext dataConext = new DataContext(option))
{
dataConext.Database.Migrate();
customer actual = new Customer()
dataConext.Customer.Add(actual);
dataConext.SaveChanges();
var expected = dataConext.Customer.FirstOrDefault();
//Assert
expected.Should().BeEquivalentTo(expected);
}
//Assert
}
}
最佳答案
创建一个实现 IDesignTimeDbContextFactory 的类在测试项目中并将测试项目设置为启动项目
public class TemporaryDataContextFactory : IDesignTimeDbContextFactory<DataContext>
{
public DataContext CreateDbContext(string[] args)
{
var option = new DbContextOptionsBuilder<DataContext>()
.UseSqlServer(@"Data Source=(LocalDb)\MSSQLLocalDB;Database=IbReport;Integrated Security=SSPI").Options;
return new DataContext(option);
}
}
关于c# - add-Migration Error 没有为此 DbContext 配置数据库提供程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52915424/