How to configure UseSqlServer?

11,288

Solution 1

 services.AddDbContext<BloggingContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("ConnectionStrings")));

for more details see -> link

Solution 2

sorry maybe some late but:

  1. Install-Package Microsoft.EntityFrameworkCore.SqlServer
  2. Add the reference: using Microsoft.EntityFrameworkCore;

Solution 3

For .NET 6.0 just do this:

builder.Services.AddDbContext<cursosContext>(options => options.UseSqlServer("name=ConnectionStrings:NombreCadena"));
Share:
11,288
Mohsen
Author by

Mohsen

Updated on June 28, 2022

Comments

  • Mohsen
    Mohsen almost 2 years

    I'm trying to configure the app to use my class (derived from DbContext) ApplicationDbContext to connect to my database. I already made the configuration file appsetting.json:

    "Data": {
        "SportStoreProducts": {
            "ConnectionStrings":"Server=(localdb)\\MSSQLLocalDB;Database=SportStore;Trusted_Connection=True;MultipleActiveResultSets=true"
        }
    }
    

    I used dependency injection to pass the object implementing IConfiguration (which is appsetting.json) through Startup construction :

    public class Startup
    {
        public Startup(IConfiguration configuration) => Configuration = configuration;
    
        public IConfiguration Configuration { get; }
    }
    

    Now I want to use this configuration file in ConfigureServices method of Startup and use extension method AddDbContext to register my ApplicationDbContext to use the SQL database (SportStore) I assigned in the configuration file :

    public void ConfigureServices(IServiceCollection services)
    {
            services.AddDbContext<ApplicationDbContext>(
                options => options.UseSqlServer(***);
    }
    

    My question is that what should I pass into the UseSqlServer method as parameters (***) so it can connect context to the SQL Server database using my supplied configuration property?

  • Admin
    Admin over 2 years
    Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.