Reputation: 553
Even finding a million question here on stachexchange none seem to fix my issue.
I have an api application in .net6.0 Which I want to add a database
The first thing apparently is that there is no startup file anymore.
my appsettings:
"ConnectionStrings": {
"ApplicationDbContext": "Server=.\\SQLEXPRESS;Database=NetworkMonitor;Trusted_Connection=True;MultipleActiveResultSets=true;"
}
my entry in program class
builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("ApplicationDbContext")));
dbcontext class:
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
:base(options)
{
}
public DbSet<HostInformation> HostInformation { get; set; }
}
when using this applicationdbcontext class i gert an error of 'unable to create an object of type applicationdbcontext'
When I add an empty constructor which I had found in some questions and answers:
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext()
{
}
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
:base(options)
{
}
public DbSet<HostInformation> HostInformation { get; set; }
}
I get 'no database provider has been configured for this context' Which seems obvious as there is an empty constructor.
Any other ideas what I am missing here?
as for packages I have entityframeworkcore .sql and .tools installed
Upvotes: 1
Views: 64
Reputation: 63
Are you reading your appsettings properly?
Maybe you are missing
builder.Configuration
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables()
.Build();
in your Program.cs file.
Before you add the DBContext with "builder.Services.AddDBContext" write the piece of code from above. If you use this check if any nuget packages are missing as well.
For ".SetBasePath()" you need - "Microsoft.Extensions.Configuration.FileExtensions" and for ".AddJsonFile" you need " Microsoft.Extensions.Configuration.Json"
If this not work check the file settings of your "appsettings.json". Maybe your not copying your appsettings.json in your directory.
Upvotes: 1