我有以下DbContext类:
public class BingoMasterDbContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Player> Players { get; set; }
public DbSet<Game> Games { get; set; }
public BingoMasterDbContext() { }
public BingoMasterDbContext(DbContextOptions<BingoMasterDbContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasOne(user => user.Player)
.WithOne(player => player.User)
.HasForeignKey<Player>(player => player.UserId);
}
}
我在StartUp.cs中的ConfigureServices方法中注册了DbContext,并将连接字符串添加到appsettings.json
services.AddControllers();
services.AddDbContext<BingoMasterDbContext>(
options => options.UseSqlServer(Configuration.GetConnectionString("Database")));
我尝试使用EF核心命令dotnet ef migrations add InitialCreate
创建初始迁移,这导致了以下错误:
尚未为此DbContext配置数据库提供程序。可以通过覆盖DbContext.OnConfiguring方法或在应用程序服务提供程序上使用AddDbContext来配置提供程序。如果使用AddDbContext,还要确保您的DbContext类型在其构造函数中接受DbContextOptions对象,并将其传递给DbContext的基构造函数。
错误消息指出,我应该注册DbContext,并在构造函数中添加一个DbContextOptions对象,然后将其传递给基构造器。我做了所有这些,但不幸的是没有运气。我不知道我做错了什么。
发布于 2020-12-07 12:13:37
问题是,我从DbContext所在的entities项目中运行了add migrations命令,但DbContext本身只在我的Startup.cs所在的API项目中注册和创建。下面的命令做到了这一点:
dotnet ef migrations add MigrationName -s mainProject -p DbContextProject
有关详细信息,请查看此Github issue
https://stackoverflow.com/questions/65180146
复制相似问题