I do a project in ASP.NET Core 6.0 and try to connect a database.
Program.cs:
using ClanSS.Data;
using ClanSS.Data.Repository;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
builder.Services.AddScoped<IRepository, Repository>();
builder.Services.AddDbContext<AppDbContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
AppDbContext.cs
using ClanSS.Models;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace ClanSS.Data
{
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options)
{ Database.EnsureCreated(); }
public DbSet<Post> Posts { get; set; }
public DbSet<Player> Team { get; set; }
}
}
appsettings.json:
{
"DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=u0925467_myblog;Trusted_Connection=true;MultipleActiveResultSets=true"
}
When I launch the project, the string in Startup is highlighted: options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
. And the follow error is shown:
Value cannot be null. Arg_ParamName_Name
What's wrong?
CodePudding user response:
Your AppSetting.json should be like this :
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=u0925467_myblog;Trusted_Connection=true;MultipleActi
veResultSets=true"
},
CodePudding user response:
This should be an error caused by not being able to get your DefaultConnection
, it may be that your ConnectionStrings
are in the wrong location.
appsetting.json should look like this:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=u0925467_myblog;Trusted_Connection=true;MultipleActiveResultSets=true"
}
}