ASP.NET 6 + Identity + Sqlite, services.AddDbContext() how?
Solution 1
Referring to ASP.NET Core 6.0 Minimal API with Entity framework core provided by @ussimandias which also worked for me.
Packages needed:
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.SqlServer
In DbContext.cs
,
override the
OnConfiguring
method to read the connection string of database from SQL server viaappsettings.json
file
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var connectionString = configuration.GetConnectionString("AppDb");
optionsBuilder.UseSqlServer(connectionString);
}
In Program.cs
,
Set Dependency Injection with service container
var connectionString = builder.Configuration.GetConnectionString("AppDb");
builder.Services.AddDbContext<EmployeeDbContext>(x => x.UseSqlServer(connectionString));
Entity Framework Database update via dotnet-ef
On Nuget Package Manager Console (Tools > Nuget Package Manager > Package Manager Console):
- Install dotnet-ef tool:
dotnet tool install dotnet-ef -f
. - Add database:
dotnet ef database update
- Add migration:
dotnet ef database update
Migration script created:
namespace MiniDemo.Migrations
{
[DbContext(typeof(EmployeeDbContext))]
[Migration("20210725025828_initialDb")]
partial class initialDb
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("ProductVersion", "5.0.8")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("MiniDemo.Model.Employee", b =>
{
b.Property<string>("EmployeeId")
.HasColumnType("nvarchar(450)");
b.Property<string>("Citizenship")
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.HasKey("EmployeeId");
b.ToTable("Employee");
});
#pragma warning restore 612, 618
}
}
}
Solution 2
Experienced the same issue i am working with .net6.0 but project is initially setup using .net5
This worked for me -
Solution 3
You have to install those packeges
- Microsoft.EntityFrameworkCore.SqlServer
- Microsoft.EntityFrameworkCore.Tools
In Program.cs
var connectionString = builder.Configuration.GetConnectionString("ConnStr");
builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString));
In appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "Server=.;Database=;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
Related videos on Youtube
Comments
-
Damn Vegetables almost 2 years
I am using a tutorial for ASP.NET Core 5.0 + SQL Server, but I am actually using ASP.NET Core 6.0 + Sqlite.
The tutorial has the following code in
StartUp.cs
public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnStr"))); }
but in my project, that file or class does not exist. There is a
Program.cs
file that has no classes or methods but just lines of code. I guessed that it is what is replacing that class, so I tried to use itbuilder.Services.AddDbContext<ApplicationDbContext>(options=> options.);
options
had no such method likeUseSqlServer
. I thought that it is because I am using Sqlite, not SQL Server, so I searched the web for an example for Sqlite but the methods that those example did not exist either. I can seeAddEntityFrameworkSqlite
, but that was about it.How can I make this work?
I have added the following relevant packages:
- Microsoft.AspNetCore.Identity
- Microsoft.AspNetCore.Identity.EntityFrameworkCore
- Microsoft.EntityFrameworkCore.Sqlite.Core
- Microsoft.EntityFrameworkCore.Tools
Other classes are the same as the original tutorial.
Here is the
DbContext
class.using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; public class ApplicationDbContext:IdentityDbContext<ApplicationUser> { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options):base(options) { } }
The
Program.cs
code I was trying to edit:using WebApplication1.Authentication; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); builder.Services.AddDbContext<ApplicationDbContext>(options=> options.); var app = builder.Build(); // Configure the HTTP request pipeline. app.UseAuthorization(); app.MapControllers(); app.Run();
-
DavidG over 2 yearsYou have no
Startup.cs
file? Did you use the console app template by accident? -
DavidG over 2 yearsAs for
options.UseSqlServer
, that won't work for SQLite at all. You need to install the EF Core SQLite provider. -
Damn Vegetables over 2 years@DavidG No, I had chosen the ASP.NET API project, you know, the thing with the Weather API. Although, the output type was set to "Console Application". I had installed ..Sqllite.Core. After seeing you comment, I installed the ...Sqlite version, too. I will test a bit if that works.
-
Damn Vegetables over 2 yearsI don't know whether it is a bug of VS 2022 Preview or not, but when I had typed
protected override void
and pressed Ctrl+Shift, there was noOnConfiguring
in the IntelliSense, so I thought it would not compile, but it compiled. After some testing, it seems thatOnConfiguring
shows up in the list if I typeoverride void
, but notprotected override void
. -
DavidG over 2 yearsIf you're running VS2022 preview, then you might be using the new templates, and you should have mentioned that in the first place. That's not a finished product yet.
-
Jason Pan over 2 yearsIt seems you forget to add package.
Microsoft.EntityFrameworkCore.Sqlite
.
-
Andrew Halil over 2 yearsSelf-contained answers are preferred over links to external sites. To write good answers refer to this link.