Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET 6 + Identity + Sqlite, services.AddDbContext() how?

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 it

builder.Services.AddDbContext<ApplicationDbContext>(options=> options.);

options had no such method like UseSqlServer. 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 see AddEntityFrameworkSqlite, 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();
like image 486
Damn Vegetables Avatar asked Sep 05 '25 03:09

Damn Vegetables


1 Answers

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 via appsettings.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
        }
    }
}
like image 113
ytan11 Avatar answered Sep 07 '25 20:09

ytan11