skip to Main Content

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?

2

Answers


  1. Your AppSetting.json should be like this :

    "ConnectionStrings": {
          "DefaultConnection": "Server=(localdb)\MSSQLLocalDB;Database=u0925467_myblog;Trusted_Connection=true;MultipleActi 
           veResultSets=true"
      },
    
    Login or Signup to reply.
  2. 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"
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search