NET 6 +标识+ Sqlite,服务,AddDbContext()如何实现?

dw1jzc5e  于 2022-12-13  发布在  SQLite
关注(0)|答案(3)|浏览(139)

我使用的是ASP.NET核心5. 0 + SQL Server的教程,但我实际上使用的是ASP.NET核心6. 0 + Sqlite。
本教程在StartUp.cs中包含以下代码

public void ConfigureServices(IServiceCollection services)  
{  
    services.AddControllers();  
    services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnStr")));  
}

但是在我的项目中,那个文件或类并不存在。有一个Program.cs文件,它没有类或方法,只有几行代码。我猜它就是替换那个类的东西,所以我尝试使用它

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

options没有像UseSqlServer这样的方法。我想这是因为我使用的是Sqlite,而不是SQL Server,所以我在网上搜索了一个Sqlite的例子,但那些例子中的方法也不存在。我可以看到AddEntityFrameworkSqlite,但仅此而已。
我怎么才能让它工作呢?
我添加了以下相关软件包:

  • Microsoft.AspNetCore.Identity
  • Microsoft.AspNetCore.Identity.EntityFrameworkCore
  • Microsoft.EntityFrameworkCore.Sqlite.Core
  • Microsoft.EntityFrameworkCore.Tools

其他类与the original tutorial相同。
下面是DbContext类。

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

sirbozc51#

参考@ussimandias提供的ASP.NET Core 6.0 Minimal API with Entity framework core,它也对我有效。

需要的软件包:

Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.SqlServer
DbContext.cs中,
覆盖OnConfiguring方法,通过appsettings.json文件从SQL Server读取数据库的连接字符串

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中,
使用服务容器设置依赖注入

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

通过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
        }
    }
}
xyhw6mcr

xyhw6mcr2#

你必须安装这些数据包

  • 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"
  }
}
3gtaxfhh

3gtaxfhh3#

添加数据库上下文- public StudentDbContext(数据库上下文选项):基础(选项){

}
    public DbSet<Student> Students { get; set; }

相关问题