How to solve 'DbContextOptionsBuilder' does not contain a definition for 'UseSqlServer' in .NET Core
By FoxLearn 11/19/2024 6:13:20 AM 31
When working with an ASP.NET Core project and trying to configure DbContext to use a connection string from your appsettings.json or another configuration source, you may encounter an error in Startup.cs
For example:
builder.Services.AddDbContext<NorthwindContext>(options=>options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
You might run into an issue where your code fails to build with an error like this:
Error CS1061 'DbContextOptionsBuilder' does not contain a definition for 'UseSqlServer' and no accessible extension method 'UseSqlServer' accepting a first argument of type 'DbContextOptionsBuilder' could be found (are you missing a using directive or an assembly reference?)
What is error CS1061 does not contain a definition for?
The CS1061 error occurs when you attempt to call a method or access a class member that does not exist.
How to resolve error “'DbContextOptionsBuilder' does not contain a definition for 'UseSqlServer'”?
The error happens because the UseSqlServer
extension method is part of the Entity Framework Core SQL Server provider.
Add the package “Microsoft.EntityFrameworkCore.SqlServer” to your project. If you haven't installed the necessary package, run the following command in your Visual Studio's Package Manager Console:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer dotnet add package Microsoft.EntityFrameworkCore.Design
Next, Include them in your Startup.cs
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.SqlServer; using Microsoft.EntityFrameworkCore.Design;
- How to use Identity column in EF7
- How to enable MultipleActiveResultSets
- How to insert master/details data in EF Code First
- Connection String in Entity Framework 6
- How to use stored procedure in Entity Framework Core
- How to use decimal precision and scale in EF Code First
- How to enable webRTC in CefSharp in C#
- How to fix 'CEF can only be initialized once per process'