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

10,430

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 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
        }
    }
}

Solution 2

Experienced the same issue i am working with .net6.0 but project is initially setup using .net5

This worked for me -

try this: https://medium.com/executeautomation/asp-net-core-6-0-minimal-api-with-entity-framework-core-69d0c13ba9ab

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"
  }
}
Share:
10,430

Related videos on Youtube

Damn Vegetables
Author by

Damn Vegetables

I don't want any damn vegetables.

Updated on June 04, 2022

Comments

  • Damn Vegetables
    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 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();
    
    • DavidG
      DavidG over 2 years
      You have no Startup.cs file? Did you use the console app template by accident?
    • DavidG
      DavidG over 2 years
      As for options.UseSqlServer, that won't work for SQLite at all. You need to install the EF Core SQLite provider.
    • Damn Vegetables
      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
      Damn Vegetables over 2 years
      I 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 no OnConfiguring in the IntelliSense, so I thought it would not compile, but it compiled. After some testing, it seems that OnConfiguring shows up in the list if I type override void , but not protected override void .
    • DavidG
      DavidG over 2 years
      If 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
      Jason Pan over 2 years
      It seems you forget to add package. Microsoft.EntityFrameworkCore.Sqlite.
  • Andrew Halil
    Andrew Halil over 2 years
    Self-contained answers are preferred over links to external sites. To write good answers refer to this link.