skip to Main Content

First, is this the correct json? Do I need to specify the ProviderName?

  "ConnectionStrings": {
    "DefaultConnection": {
      "ConnectionString": "Data Source=(local);Initial Catalog=MyDB;Integrated Security=SSPI;",
      "ProviderName": "System.Data.SqlClient"
    }
  }

Second, the Program.cs file created by Visual Studio doesn’t seem to have anywhere to insert a bunch of Dependency Injection type code. So where should it go?

Third, Microsoft’s sample code for a Configuration object show a method called "GetConnectionString", yet the compiler says that method doesn’t exist. Thank you, Bill.

I’d appreciate not just a fragment of code but also exactly where to place it, and which usings are necessary. Because, honestly, I’ve tried to piece this together every which way and have read all the StackOverflow articles, without success.

2

Answers


  1. Chosen as BEST ANSWER

    You know what? Just forget it. I've changed my project from .Net Core to .Net Framework. For one thing, I tried also creating a .Net Core project configured for database connectivity. And that introduced Entity Framework, which is the most obnoxious thing ever. .Net Core, with all of its DI and its nested parentheses constructs, is the most obtuse looking code I've ever seen. And then the documentation stinks, and the incomplete code examples get you nowhere. .Net Core is like evolution in reverse.


  2. First, is this the correct json? Do I need to specify the ProviderName?

    There is no need to set the ProviderName, the correct connection string is like below:

      "ConnectionStrings": {
        "DefaultConnection": "Server=(localdb)\mssqllocaldb;Database=xxxx;Trusted_Connection=True;MultipleActiveResultSets=true"
      }
    

    Second, the Program.cs file created by Visual Studio doesn’t seem to have anywhere to insert a bunch of Dependency Injection type code. So where should it go?

    After .net 6, the program.cs is the file which could configure the services.

    Something like below:

    builder.Services.AddDbContext<MyDbContext>(options =>
        options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
    

    Third, Microsoft’s sample code for a Configuration object show a method called "GetConnectionString", yet the compiler says that method doesn’t exist.

    The GetConnectionString method is available on the Microsoft.Extensions.Configuration namespace, you could make sure you have referenced it and make user you have set the builder well var builder = WebApplication.CreateBuilder(args).

    If you don’t have it, you could also use other method to get it.

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search