简体   繁体   中英

ASP.NET WebAPI DbContext - Unable to create an object of type / No database provider has been configured

I've been following this tutorial: YT Tutorial (starts at my issue) with the exception that I'm on .NET6. When I add a migration The two errors I can get are either:

  • No database provider has been configured for this DbContext (...)
  • Unable to create an object of type 'PmrDbContext'. (...) <- this happens if I leave out a default constructor

Program.cs:

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
var app = builder.Build();
string connectionString = builder.Configuration.GetConnectionString("DevConnection");
builder.Services.AddDbContext<PmrDbContext>(options => options.UseSqlServer(connectionString));

PmrDbContext.cs:

public class PmrDbContext : DbContext
{
    // default constructor there - one or the other error

    public PmrDbContext(DbContextOptions<PmrDbContext> options) : base(options)
    {

    }

    public DbSet<Employee> Employees { get; set; }
}

ConnectionString:

"ConnectionStrings": {
  "DevConnection": "Server=(local)\\sqlexpress;Database=PMRHomeDB;Trusted_Connection=True;MultipleActiveResultSets=True;"
 }

Do I need to create a DB first? Is this not a code-first EF solution?

It is not possible to change Services after Build(), so I moved the AddDbContext before it - also leaving out the default constructor in my DbContext class.

string connectionString = builder.Configuration.GetConnectionString("DevConnection");
builder.Services.AddDbContext<PmrDbContext>(options => options.UseSqlServer(connectionString));
var app = builder.Build();

I ran the project and it was working. Also the Add-Migration also worked this way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM