How to configure UseSqlServer?
Solution 1
services.AddDbContext<BloggingContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("ConnectionStrings")));
for more details see -> link
Solution 2
sorry maybe some late but:
- Install-Package Microsoft.EntityFrameworkCore.SqlServer
- 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"));
Mohsen
Updated on June 28, 2022Comments
-
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 fileappsetting.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 isappsetting.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 ofStartup
and use extension methodAddDbContext
to register myApplicationDbContext
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 over 2 yearsYour 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.