ASP.NET 6 + Identity + Sqlite, services.AddDbContext() 怎么样?

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

我正在使用 ASP.NET Core 5.0 + SQL 服务器的教程,但我实际上使用的是 ASP.NET Core 6.0 + Sqlite。

教程在StartUp.cs

中有如下代码
public void ConfigureServices(IServiceCollection services)  
{  
    services.AddControllers();  
    services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnStr")));  
}  

但在我的项目中,该文件或 class 不存在。有一个 Program.cs 文件没有 classes 或方法,只有几行代码。我猜它是 class 的替代品,所以我尝试使用它

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

options 没有像 UseSqlServer 这样的方法。我认为这是因为我使用的是 Sqlite,而不是 SQL Server,所以我在网上搜索了 Sqlite 的示例,但这些示例的方法也不存在。我可以看到 AddEntityFrameworkSqlite,但仅此而已。

我怎样才能使这个工作?

我添加了以下相关包:

其他class同the original tutorial

这里是DbContextclass.

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

public class ApplicationDbContext:IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options):base(options)
    {
    }
}

我试图编辑的 Program.cs 代码:

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();

我在使用 .net6.0 时遇到了同样的问题,但项目最初是使用 .net5 设置的

这对我有用 -

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

指的是@ussimandias 提供的ASP.NET Core 6.0 Minimal API with Entity framework core,它也对我有用。

需要的包:

Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.SqlServer

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

Program.cs,

Set Dependency Injection with service container

var connectionString = builder.Configuration.GetConnectionString("AppDb");
builder.Services.AddDbContext<EmployeeDbContext>(x => x.UseSqlServer(connectionString));

Entity Framework 通过 dotnet-ef 更新数据库

在 Nuget 包管理器控制台上(工具 > Nuget 包管理器 > 包管理器控制台):

  • 安装 dotnet-ef 工具:dotnet tool install dotnet-ef -f.
  • 添加数据库:dotnet ef database update
  • 添加迁移:dotnet ef database update

已创建迁移脚本:

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

您必须安装软件包

  • Microsoft.EntityFrameworkCore.SqlServer
  • Microsoft.EntityFrameworkCore.Tools

在Program.cs

var connectionString = builder.Configuration.GetConnectionString("ConnStr");
builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString));

在appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DefaultConnection": "Server=.;Database=;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}