'options.UseSqlServer returns Error in startup.cs
I'm developing a test Project using asp.net core. For Connecting to database I'm using Entity framework. I add appsetings.json file to the project and change the connection string as follows:
{
"ConnectionStrings": {
"DefaultConnection": "Server=.\\mihanrayan;Initial Catalog=SportsStore;User = sa; Password = 123456"
}
}
sql version is : mssql 2008 r2
in startup.cs class I add codes below:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration["Data:SportStoreProducts:ConnectionString"]));
services.AddTransient<IProductRepository, EFProductRepository>();
}
but
options.UseSqlServer(
Configuration["Data:SportStoreProducts:ConnectionString"]));
returns this error:
An exception of type 'System.ArgumentNullException' occurred in Microsoft.EntityFrameworkCore.SqlServer.dll but was not handled in user code
Additional information: Value cannot be null.
Solution 1:[1]
Configuration["Data:SportStoreProducts:ConnectionString"])
is returning null.
"Data:SportStoreProducts:ConnectionString"
should probably be
"ConnectionStrings:Defaultconnection"
Solution 2:[2]
It should be like as shown below:
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
Solution 3:[3]
Install this nuGet package:
"Microsoft.EntityFrameworkCore.SqlServer"
Upon spending hours searching for the fix, this was what worked for me.
NB: select the same version as your .net version
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | cwharris |
Solution 2 | Riddhi |
Solution 3 | Djimatey Evans |