c# - add-Migration Error 没有为此 DbContext 配置数据库提供程序

标签 c# entity-framework ef-core-2.1

我正在尝试向 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 单元测试项目

  1. 域(Poco类)
  2. 存储库(.Net Core 2.1,EntitiFrameworkCore 2.1.4)
  3. 存储库测试

这是我的 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/

相关文章:

c# - 在 Task.Run 中使用 async/await 在 WinForms 上访问 UI 控件

c# - 如何在 Entity Framework 中使用 LINQ-to-SQL 回滚事务?

c# - 我将如何将以下 T-SQL 语句翻译成 Linq

ef-core-2.1 - 使用 EF core 2.1 调用 DbFunction

c# - 覆盖 AspNetCore.Identity 表中的默认索引

c# - 使用操作过滤器修改操作内的值

c# - 在 C# 中计划任务并继续

c# - 在 C# 中将字符串转换为字节数组

c# - Entity Framework 6 两个不同的集合引用同一个实体

c# - EF Core 2.1 [更改跟踪] - 保存所有相关实体