简体   繁体   English

带有 EntityFrameworkCore 的 ASP.NET Core 中的 SQLite

[英]SQLite in ASP.NET Core with EntityFrameworkCore

How do you add and use an SQLite database in an ASP.NET Core web application, using EntityFramework 7 ?如何使用 EntityFramework 7 在 ASP.NET Core Web 应用程序中添加和使用 SQLite 数据库?

I dived into ASP.NET Core the moment I heard about it and created my first web application, I suddenly had a bunch of data that I wanted to store and SQLite seemed like the obvious choice.在我听说 ASP.NET Core 并创建我的第一个 Web 应用程序的那一刻,我一头扎进了它,我突然想存储一堆数据,而 SQLite 似乎是显而易见的选择。
Since I wanted it to stay with my application, keep it lightweight, simple and avoid setting up a separate database.由于我希望它与我的应用程序保持一致,因此请保持轻量级、简单并避免设置单独的数据库。

So how would one go about creating an SQLite database in ASP.NET Core?那么如何在 ASP.NET Core 中创建 SQLite 数据库呢?

  • ASP.NET Core - now formerly known as ASP.NET MVC 6 ASP.NET Core - 现在以前称为 ASP.NET MVC 6
  • EntityFramework Core - now formerly known as EntityFramework 7 EntityFramework Core - 现在以前称为 EntityFramework 7

Update: November 4th, 2016.更新:2016 年 11 月 4 日。
Reformatting - pictures to code examples.重新格式化 - 图片到代码示例。
Info : Keep in mind that in some code examples, code that was generated by the visual studio template have been omitted.信息:请记住,在某些代码示例中,已省略了由 Visual Studio 模板生成的代码。

Update: July 11th, 2016.更新:2016 年 7 月 11 日。
.NET Core and EntityFrameWork Core version 1.0 is upon us! .NET Core 和 EntityFrameWork Core 1.0 版即将发布!
So this guide deserves a little update所以本指南值得一点更新

Step 1:第 1 步:
Create your application.创建您的应用程序。
在此处输入图片说明

Step 2:第 2 步:
Get the necessary packages获取必要的包
Microsoft.EntityFrameworkCore 1.0.0 Microsoft.EntityFrameworkCore 1.0.0
Microsoft.EntityFrameworkCore.SQlite 1.0.0 Microsoft.EntityFrameworkCore.SQlite 1.0.0

Step 3:第 3 步:
Create your context:创建您的上下文:
(The Context will be a class that you create) (上下文将是您创建的类)

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

Step 4:第 4 步:
Add your context to your services:将您的上下文添加到您的服务中:
(Located in your Startup class) (位于您的 Startup 类中)

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

Step 5:第 5 步:
Create your database on startup, by adding it to the startup method在启动时创建数据库,将其添加到启动方法中
(Located in the Startup class) (位于 Startup 类中)

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

Et Voíla!等等!
Now you will be able to use SQLite in your ASP.NET Core applications.现在,您将能够在 ASP.NET Core 应用程序中使用 SQLite。
The old guide still applies regarding how you create your models as well as using your database context.旧指南仍然适用于如何创建模型以及使用数据库上下文。


Update: May 28th, 2016.更新:2016 年 5 月 28 日。
.NET Core RC2 and EntityFramework Core RC1 have been released. .NET Core RC2 和 EntityFramework Core RC1 已经发布。
They have improved and simplified the steps for setting up SQLite.他们改进并简化了设置 SQLite 的步骤。
But I'm experiencing some trouble with it and can't replicate it, because of an error with the Newtonsoft.Json library and NuGet.但是我遇到了一些问题并且无法复制它,因为 Newtonsoft.Json 库和 NuGet 出现错误。

I recommend sticking to the RC1 libraries if you want to do this, for now!如果你想这样做,我建议现在坚持使用 RC1 库!


Step 1:第 1 步:
Create your ASP.NET web application创建您的 ASP.NET Web 应用程序

ASP.NET5WebApp

Step 2:第 2 步:
Go to Tools -> Nuget Packet Manager -> Manage Nuget Packages for Solution.转到工具 -> Nuget 包管理器 -> 管理解决方案的 Nuget 包。
Search for EntityFramework.SQLite and check the Include prelease box.搜索EntityFramework.SQLite并选中Include prelease框。
Install the package安装包

NugetEF7Sqlite

Step 3: Creating a context第 3 步:创建上下文
Create a context class for your database.为您的数据库创建一个上下文类。
Call it whatever you want, but let's go with something that's customiary, like MyDbContext .随便你怎么称呼它,但让我们用一些习惯的东西,比如MyDbContext Make your new class inherit the DbContext class and override the OnConfiguring method and define your connection like so:让你的新类继承 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);
    }
}

Step 4:第 4 步:
Go to the Startup.cs and make sure your database is created at the start of your web application:转到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();
        }

    }

Secondly we need to add the service:其次我们需要添加服务:

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

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

Step 5: Defining your Models第 5 步:定义模型
Create your models and go to MyDbContext.cs and add a new property for each of your new models (given that you want a table for each!)创建您的模型并转到MyDbContext.cs并为您的每个新模型添加一个新属性(假设您想要每个模型!)
Here's an example:下面是一个例子:
My Model:我的型号:

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

    public string Title { get; set; }

    public string Description { get; set; }

    public string UrlSlug { get; set; }
}

Adding it to my context:将其添加到我的上下文中:

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

Step 6: Using the the context第 6 步:使用上下文
Go to your HomeController and add a new field to your controller.转到您的 HomeController 并向您的控制器添加一个新字段。
private readonly MyDbContext _myDbContext = new MyDbContext();
And use it in an ActionResult by passing it to the returned view: (Now lets assume we have a category in our database)并通过将其传递给返回的视图在 ActionResult 中使用它:(现在假设我们的数据库中有一个类别)

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

So by going to your Index view, you can use our imaginary data from the database.因此,通过转到您的索引视图,您可以使用我们从数据库中获得的虚构数据。 By defining a model in the top of your view like so:通过在视图顶部定义模型,如下所示:

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


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

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

Now by starting our web application and going to the assigned address we should see a default html page with a fancy bootstrap header, showing this on the page:现在通过启动我们的 web 应用程序并转到分配的地址,我们应该看到一个带有花哨的引导程序标题的默认 html 页面,在页面上显示:
网页

The second line is (or would be) the title of our first category in our database.第二行是(或将是)我们数据库中第一个类别的标题。

Entity Framework 7 Docs实体框架 7 文档

This is my first Q&A - if you have any input or something that needs clarifying don't hesitate to comment.这是我的第一个问答 - 如果您有任何意见或需要澄清的内容,请随时发表评论。
This is a very basic example of how to implement an SQLite database into an ASP.NET Core MVC web application.这是一个非常基本的示例,说明如何将 SQLite 数据库实现到 ASP.NET Core MVC Web 应用程序中。
Do note that there is several ways to set the connection string for the database, how to use the context and that EntityFramework 7 is still a prerelease请注意,有多种方法可以为数据库设置连接字符串、如何使用上下文以及 EntityFramework 7 仍然是预发布版

If you want to create an ASP.NET Core web application using SQLite for the database, I highly recommend using Yeoman to scaffold the app for you.如果您想使用 SQLite 为数据库创建 ASP.NET Core Web 应用程序,我强烈建议您使用Yeoman为您构建应用程序。 You need to first install .NET Core 1.1 SDK (Visual Studio 2015 seems to only include SDK versions 1.0.0 and 1.0.1 at the moment).您需要先安装.NET Core 1.1 SDK (Visual Studio 2015 目前似乎只包含 SDK 版本 1.0.0 和 1.0.1)。 You then need to install Node.js which comes with npm and then install the following npm packages: yo and generator-aspnet .然后,您需要安装 npm 附带的Node.js ,然后安装以下 npm 包: yogenerator-aspnet Then all you have to do is run yo aspnet and answer a few questions.然后你所要做的就是运行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

Afterwards, you will get the following response:之后,您将得到以下响应:

 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

Run dotnet restore , dotnet ef database update , and then dotnet run and go to localhost:5000 to make sure the project is running.运行dotnet restoredotnet ef database update ,然后dotnet run并转到localhost:5000以确保项目正在运行。

Now you can open the project in Visual Studio 2015 (assuming you're on Windows) or Visual Studio Code.现在,您可以在 Visual Studio 2015(假设您使用的是 Windows)或 Visual Studio Code 中打开该项目。

使用 Yeoman 生成的 ASP.NET Core Web 应用程序

The great thing about this is that Startup.cs , project.json , and appsettings.json files are setup to use SQLite.这样做的appsettings.jsonStartup.csproject.jsonappsettings.json文件被设置为使用 SQLite。 Also, a SQLite database is created for you:此外,还为您创建了一个 SQLite 数据库:

Startup.cs:启动.cs:

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

project.json:项目.json:

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

appsettings.json appsettings.json

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

Your SQLite database will be located in bin/Debug/netcoreapp1.0 .您的 SQLite 数据库将位于bin/Debug/netcoreapp1.0 In my case, it is located in C:\\Development\\WebApplication\\bin\\Debug\\netcoreapp1.0\\WebApplication.db就我而言,它位于C:\\Development\\WebApplication\\bin\\Debug\\netcoreapp1.0\\WebApplication.db

If you want to rename the SQLite database, modify appsettings.json file and run dotnet ef database update .如果要重命名 SQLite 数据库,请修改appsettings.json文件并运行dotnet ef database update

To learn more about using SQLite database with .NET Core and EF Core, check out this article: .NET Core - New Database要了解有关在 .NET Core 和 EF Core 中使用 SQLite 数据库的更多信息,请查看这篇文章: .NET Core - 新数据库

  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创建 DBContext 类添加 SQLite 连接配置

     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

https://fullstack-lab.co.in/Sqlite-entity-framework-core-quick-start https://fullstack-lab.co.in/Sqlite-entity-framework-core-quick-start

This article provides simple steps to use SQLite with Asp.net core 3.1本文提供了在 Asp.net core 3.1 中使用 SQLite 的简单步骤

In dotnet 6 : Your DbContext constructor should look like this: (remove OnConfiguring method from your DbContext.在 dotnet 6 中:您的 DbContext 构造函数应如下所示:(从您的 DbContext 中删除 OnConfiguring 方法。

    public PaymentDbContext(DbContextOptions<PaymentDbContext> options) : base(options)
{

}

and in program.cs file, add your service like this:在 program.cs 文件中,像这样添加你的服务:

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

dbPath is your database address. dbPath 是您的数据库地址。

if you want to update your database and your dbContext file located in a different solutions don't forget to use --startup-project in dotnet ef database update command :) ex:如果要更新位于不同解决方案中的数据库和 dbContext 文件,请不要忘记在 dotnet ef 数据库更新命令中使用 --startup-project :) 例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在ASP.Net Core 1.0中注册通用EntityFrameworkCore DbContext - Register generic EntityFrameworkCore DbContext in ASP.Net Core 1.0 如何从 ASP.NET Core 3.1 中的 EntityFrameworkCore 3 中删除依赖项 - How to remove dependency from EntityFrameworkCore 3 in ASP.NET core 3.1 在ASP.NET Core中,如何使用sqlite - In ASP.NET Core, how to use sqlite 使用ASP.NET Core从MS EntityFrameworkCore中的Json文件获取记录 - Get records from Json file in MS EntityFrameworkCore using asp.net core 无法在 ASP.NET Core 中安装“Microsoft.EntityFrameworkCore.Tools.Dotnet” - Can't install "Microsoft.EntityFrameworkCore.Tools.Dotnet" in ASP.NET Core 如何在 ASP.NET CORE 3.1.1 中具有 ForeignKey 的 Map(使用 AutoMapper)实体(C#,EntityFrameworkCore) - How to Map (using AutoMapper) entities that have a ForeignKey in ASP.NET CORE 3.1.1 (C#,EntityFrameworkCore) ASP.NET Core 2 无法解析 Microsoft EntityFrameworkCore DbContext 类型的服务 - ASP.NET Core 2 Unable to resolve service for type Microsoft EntityFrameworkCore DbContext Asp.Net Core 1.0.0:Npgsql.EntityFrameworkCore.PostgreSQL迁移错误 - Asp.Net Core 1.0.0: Npgsql.EntityFrameworkCore.PostgreSQL Migration error 升级到 ASP.NET Core 5.0 时 Microsoft.EntityFrameworkCore.Relational 的版本冲突 - Version conflict for Microsoft.EntityFrameworkCore.Relational when upgrading to ASP.NET Core 5.0 .Net核心和EntityFrameworkCore - .Net Core And EntityFrameworkCore
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM