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

问题描述 投票:0回答:4

我使用的是 ASP.NET Core 5.0 + SQL Server 的教程,但我实际上使用的是 ASP.NET Core 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

其他课程与原教程相同

这是

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();
c# sqlite asp.net-core asp.net-identity
4个回答
36
投票

参考@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
        }
    }
}

13
投票

你必须安装这些包

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

在Program.cs中

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
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"
  }
}

0
投票

添加数据库上下文 - public StudentDbContext(DbContextOptions options) : base(options) {

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

0
投票

对我有用:

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

但是这是好的

services.AddSqlServer<ApplicationDbContext>(configuration.GetConnectionString("DefaultConnection"));
© www.soinside.com 2019 - 2024. All rights reserved.