使用EntityFrameworkCore在ASP.NET Core中使用SQLite

75

如何在使用EntityFramework 7的ASP.NET Core Web应用程序中添加和使用SQLite数据库?

当我第一次听到ASP.NET Core时,我就立刻深入研究并创建了我的第一个Web应用程序。突然间,我有了一堆想要存储的数据,而SQLite似乎是一个显而易见的选择。
由于我希望它随我的应用程序一起存在,保持轻量级、简单,并避免设置一个单独的数据库。

那么怎样在ASP.NET Core中创建SQLite数据库呢?

  • ASP.NET Core - 现在正式称为ASP.NET MVC 6
  • EntityFramework Core - 现在正式称为EntityFramework 7

1
本文提供了使用SQLite与asp.net core的简单步骤。 - saravana manikandan
4个回答

153
更新:2016年11月4日。
重新格式化 - 将图片转换为代码示例。
信息: 请记住,在某些代码示例中,由Visual Studio模板生成的代码已被省略。

更新:2016年7月11日。
.NET Core和EntityFrameWork Core版本1.0正式发布!
因此,本指南应进行一些更新。

步骤1:
创建您的应用程序。
enter image description here

步骤2:
获取必要的软件包
Microsoft.EntityFrameworkCore 1.0.0
Microsoft.EntityFrameworkCore.SQlite 1.0.0

步骤3:
创建您的上下文:
(上下文将是您创建的类)

public class DatabaseContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlite("Filename=MyDatabase.db");
    }
}

步骤4:
将您的上下文添加到您的服务中:
(位于您的启动类中)

public void ConfigureServices(IServiceCollection services)
{
    services.AddEntityFrameworkSqlite().AddDbContext<DatabaseContext>();
}

步骤 5:
通过将数据库添加到启动方法(位于启动类中),在启动时创建您的数据库。

public Startup(IHostingEnvironment env)
{
    using(var client = new DatabaseContext())
    {
        client.Database.EnsureCreated();
    }
}

Et Voíla!
现在您可以在ASP.NET Core应用程序中使用SQLite。
关于如何创建模型以及使用数据库上下文,旧指南仍然适用。


更新:2016年5月28日。
.NET Core RC2和EntityFramework Core RC1已发布。
它们改进并简化了设置SQLite的步骤。
但是我遇到了一些问题,由于Newtonsoft.Json库和NuGet的错误,无法复制它。

如果您想这样做,我建议暂时坚持使用RC1库!


步骤1:
创建ASP.NET Web应用程序。

ASP.NET5WebApp

步骤2:
转到“工具”->“Nuget Packet Manager”->“管理解决方案的Nuget包”。
搜索EntityFramework.SQLite并选中Include prelease框。
安装软件包

NugetEF7Sqlite

步骤3:创建上下文
为您的数据库创建一个上下文类。
称其为任何您想要的内容,但让我们使用惯例,例如MyDbContext。 使您的新类继承DbContext类并覆盖OnConfiguring方法,定义连接如下:

public class MyDbContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        var connectionStringBuilder = new SqliteConnectionStringBuilder { DataSource = "MyDb.db" };
        var connectionString = connectionStringBuilder.ToString();
        var connection = new SqliteConnection(connectionString);

        optionsBuilder.UseSqlite(connection);
    }
}

步骤 4:
转到 Startup.cs 并确保在 Web 应用程序启动时创建了您的数据库:

public Startup(IHostingEnvironment env)
    {
        // Set up configuration sources.
        var builder = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);         


        using (var db = new MyDbContext())
        {
            db.Database.EnsureCreated();
            db.Database.Migrate();
        }

    }

第二步,我们需要添加该服务:

public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc();

        services.AddEntityFramework()
        .AddSqlite()
        .AddDbContext<MyDbContext>();
    }

步骤5:定义您的模型
创建您的模型,并进入MyDbContext.cs,为每个新模型添加一个新属性(如果您想要每个都有一个表格!)
以下是一个示例:
我的模型:

public class Category
{
    public int Id { get; set; }

    public string Title { get; set; }

    public string Description { get; set; }

    public string UrlSlug { get; set; }
}

将其添加到我的上下文中:

public class MyDbContext : DbContext
{
    public DbSet<Category> Categories { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        var connectionStringBuilder = new SqliteConnectionStringBuilder { DataSource = "MyDb.db" };
        var connectionString = connectionStringBuilder.ToString();
        var connection = new SqliteConnection(connectionString);

        optionsBuilder.UseSqlite(connection);
    }
}

第六步:使用上下文
打开你的HomeController,并在控制器中添加一个新的字段。
private readonly MyDbContext _myDbContext = new MyDbContext();
然后在ActionResult中使用它,通过将其传递给返回的视图:(现在假设我们在数据库中有一个类别)

public IActionResult Index()
{
    var category = _myDbContext.Categories.First();
    return View(category);
}

通过进入您的索引视图,您可以使用我们从数据库中获取的虚拟数据。在视图顶部定义模型,如下所示:

@model  MyNameSpace.Models.Category
@{
   ViewData["Title"] = "Hey Ho! SO!";
}


<div class="page-header">
    <h1>@ViewData["Title"]</h1>
</div>

<div class="container">
    @Model.Title
</div>

现在启动我们的 Web 应用程序,然后转到分配的地址,我们应该看到一个默认的 HTML 页面,其中有一个漂亮的 bootstrap header,在页面上显示如下内容:
webpage

第二行是(或将是)我们数据库中第一个类别的标题。

Entity Framework 7 文档

这是我的第一个问答 - 如果您有任何意见或需要澄清的问题,请随时发表评论。
这是如何在 ASP.NET Core MVC Web 应用程序中实现 SQLite 数据库的非常基本的示例。
请注意,有几种设置数据库连接字符串的方法,如何使用上下文以及 EntityFramework 7 仍处于预发布状态。


1
这在2020年仍然适用吗,在Core 3.1中? - rizu
2
@rizu 是的,没错。 - Cicero
https://learn.microsoft.com/en-us/ef/core/get-started/overview/first-app?tabs=netcore-cli - KuhakuPixel

18
如果您想创建一个使用SQLite作为数据库的ASP.NET Core Web应用程序,我强烈推荐使用Yeoman为您构建应用程序。您需要先安装.NET Core 1.1 SDK(目前Visual Studio 2015似乎只包括SDK版本1.0.0和1.0.1)。然后,您需要安装Node.js,它带有npm,然后安装以下npm软件包:yogenerator-aspnet。然后,您只需要运行yo aspnet并回答几个问题即可。
C:\Development>yo aspnet
? ==========================================================================
We're constantly looking for ways to make yo better!
May we anonymously report usage statistics to improve the tool over time?
More info: https://github.com/yeoman/insight & http://yeoman.io
========================================================================== Yes

     _-----_     ╭──────────────────────────╮
    |       |    │      Welcome to the      │
    |--(o)--|    │  marvellous ASP.NET Core │
   `---------´   │        generator!        │
    ( _´U`_ )    ╰──────────────────────────╯
    /___A___\   /
     |  ~  |
   __'.___.'__
 ´   `  |° ´ Y `

? What type of application do you want to create? Web Application
? Which UI framework would you like to use? Bootstrap (3.3.6)
? What's the name of your ASP.NET application? WebApplication

之后,您将获得以下响应:

 Your project is now created, you can use the following commands to get going
    cd "WebApplication"
    dotnet restore
    dotnet build (optional, build will also happen when it's run)
    dotnet ef database update (to create the SQLite database for the project)
    dotnet run

运行 dotnet restoredotnet ef database update,然后运行 dotnet run 并转到 localhost:5000 确保项目正在运行。
现在您可以在 Visual Studio 2015(假设您正在 Windows 上)或 Visual Studio Code 中打开项目。

ASP.NET Core web application generated using Yeoman

这里的好处是,Startup.csproject.jsonappsettings.json 文件已经设置为使用 SQLite。此外,一个 SQLite 数据库也已经为您创建:

Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));
}

project.json:

{
    "Microsoft.EntityFrameworkCore.Sqlite": "1.1.0",
    "Microsoft.EntityFrameworkCore.Sqlite.Design": {
      "version": "1.1.0",
      "type": "build"
    }
}

appsettings.json

{
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=WebApplication.db"
  }
}

你的SQLite数据库将位于bin/Debug/netcoreapp1.0。在我的情况下,它位于C:\Development\WebApplication\bin\Debug\netcoreapp1.0\WebApplication.db 如果你想重命名SQLite数据库,请修改appsettings.json文件并运行dotnet ef database update
要了解有关使用.NET Core和EF Core的SQLite数据库的更多信息,请查看此文章:.NET Core - New Database

指定的框架 'Microsoft.NETCore.App',版本 '1.1.0' 未找到。因此现在需要 1.1.0 -- yo aspnet 生成器与 v 1.0.1 不兼容。 - hB0
1
如果您要使用Yeoman和Visual Studio,您有两个选择:1)下载.NET Core 1.1 SDK更新NuGet到Beta版。2)手动编辑package.json并将“1.1.0-preview4-final”更改为“1.0.0-preview2-003131”(还要将“1.1.0”更改为“1.0.1”)。如果您创建了一个global.json文件,请确保sdk.version仍然是“1.0.0-preview2-003131”,无论您选择哪个版本。微软正在放弃package.json,转而使用.csproj,因此需要识别package.json - kimbaudi
我的应用程序正在使用开发设置,我无法创建使用Sqlite的迁移。这是我的问题,如果您能帮忙:https://stackoverflow.com/questions/49598638/dotnet-ef-migrations-using-sql-server-when-development-environment-is-set-to-use?noredirect=1#comment86204585_49598638 - iJK

5
  1. Install Below mentioned packages

     PM> Install-Package Microsoft.EntityFrameworkCore
     PM> Install-Package Microsoft.EntityFrameworkCore.Sqlite
     PM> Install-Package Microsoft.EntityFrameworkCore.Tools
    
  2. Create Models

  3. Create DBContext class add SQLite connection configuration

     protected override void OnConfiguring(DbContextOptionsBuilder options)
         => options.UseSqlite("Data Source=DBFileName.db");
    
  4. Run migration commands to start using it

     PM> add-migration <MigrationName>  //Ex: add-migration IntialMigration
     PM> update-database
    

本文提供了在 Asp.net core 3.1 中使用 SQLite 的简单步骤。

注意:本文中的链接提供了 Sqlite 和 Entity Framework Core 的快速入门指南。


好的,下次我会确保做到。谢谢。 - saravana manikandan

2
在 .NET 6 中: 您的 DbContext 构造函数应该如下所示:(从您的 DbContext 中删除 OnConfiguring 方法)。
    public PaymentDbContext(DbContextOptions<PaymentDbContext> options) : base(options)
{

}

在 program.cs 文件中,要像这样添加您的服务:

并在Program.cs文件中像这样添加您的服务:

builder.Services.AddDbContext<PaymentDbContext>(options =>
options.UseSqlite($"Data Source={dbPath}"));

dbPath是您的数据库地址。

如果您想更新位于不同解决方案中的数据库和dbContext文件,请不要忘记在dotnet ef database update命令中使用--startup-project :) 例如:

dotnet ef database update --startup-project ../PaymentProject.Api/PaymentProject.Api.csproj 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接