ASP.NET Core中的SQLite与EntityFrameworkCore

Cic*_*ero 37 c# sqlite asp.net-mvc entity-framework-core asp.net-core-mvc

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

当我听到它并创建了我的第一个Web应用程序时,我潜入了ASP.NET Core,我突然想要存储一堆数据,而SQLite似乎是明显的选择.
因为我希望它与我的应用程序保持一致,所以要保持它的轻量级,简单并避免设置单独的数据库.

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

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

Cic*_*ero 95

更新:2016
11月4日.重新格式化 - 图片到代码示例.
信息:请记住,在某些代码示例中,已省略了由visual studio模板生成的代码.

更新:2016年7月11日
..NET Core和EntityFrameWork核心版本1.0正在发布!
因此本指南值得一点更新

第1步:
创建您的应用程序.
在此输入图像描述

第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");
    }
}
Run Code Online (Sandbox Code Playgroud)

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

public void ConfigureServices(IServiceCollection services)
{
    services.AddEntityFrameworkSqlite().AddDbContext<DatabaseContext>();
}
Run Code Online (Sandbox Code Playgroud)

步骤5:
在启动时创建数据库,方法是将其添加到启动方法
(位于Startup类中)

public Startup(IHostingEnvironment env)
{
    using(var client = new DatabaseContext())
    {
        client.Database.EnsureCreated();
    }
}
Run Code Online (Sandbox Code Playgroud)

EtVolala!
现在,您将能够在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数据包管理器 - >管理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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

    }
Run Code Online (Sandbox Code Playgroud)

其次我们需要添加服务:

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

        services.AddEntityFramework()
        .AddSqlite()
        .AddDbContext<MyDbContext>();
    }
Run Code Online (Sandbox Code Playgroud)

第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; }
}
Run Code Online (Sandbox Code Playgroud)

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

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

步骤6:使用上下文
转到HomeController并向控制器添加新字段.
private readonly MyDbContext _myDbContext = new MyDbContext();
并通过将其传递给返回的视图在ActionResult中使用它:( 现在假设我们的数据库中有一个类别)

public IActionResult Index()
{
    var category = _myDbContext.Categories.First();
    return View(category);
}
Run Code Online (Sandbox Code Playgroud)

因此,通过转到Index视图,您可以使用数据库中的虚数据.通过在视图顶部定义模型,如下所示:

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


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

<div class="container">
    @Model.Title
</div>
Run Code Online (Sandbox Code Playgroud)

现在,通过启动我们的Web应用程序并转到指定的地址,我们应该看到一个带有花哨的引导程序头的默认html页面,在页面上显示:
网页

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

实体框架7文档

这是我的第一个问答 - 如果您有任何意见或需要澄清的内容,请不要犹豫.
这是如何将SQLite数据库实现到ASP.NET Core MVC Web应用程序的一个非常基本的示例.
请注意,有几种方法可以为数据库设置连接字符串,如何使用上下文以及EntityFramework 7仍然是一个预发行版

  • @rizu 是的,确实如此。 (2认同)

kim*_*udi 7

如果您想使用SQLite为数据库创建ASP.NET Core Web应用程序,我强烈建议您使用Yeoman为您构建应用程序.您需要先安装.NET Core 1.1 SDK(Visual Studio 2015目前似乎只包含SDK版本1.0.0和1.0.1).然后,您需要安装npm附带的Node.js,然后安装以下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
Run Code Online (Sandbox Code Playgroud)

之后,您将得到以下回复:

 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 Code Online (Sandbox Code Playgroud)

运行dotnet restore,dotnet ef database update然后dotnet run转到以localhost:5000确保项目正在运行.

现在,您可以在Visual Studio 2015中打开项目(假设您使用的是Windows)或Visual Studio Code.

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

关于这个伟大的事情是Startup.cs,project.jsonappsettings.json文件设置使用SQLite.此外,还为您创建了一个SQLite数据库:

Startup.cs:

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

project.json:

{
    "Microsoft.EntityFrameworkCore.Sqlite": "1.1.0",
    "Microsoft.EntityFrameworkCore.Sqlite.Design": {
      "version": "1.1.0",
      "type": "build"
    }
}
Run Code Online (Sandbox Code Playgroud)

appsettings.json

{
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=WebApplication.db"
  }
}
Run Code Online (Sandbox Code Playgroud)

您的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 - 新数据库


sar*_*dan 5

  1. 安装下面提到的软件包

     PM> Install-Package Microsoft.EntityFrameworkCore
     PM> Install-Package Microsoft.EntityFrameworkCore.Sqlite
     PM> Install-Package Microsoft.EntityFrameworkCore.Tools
    
    Run Code Online (Sandbox Code Playgroud)
  2. 创建模型

  3. 创建DBContext类添加SQLite连接配置

     protected override void OnConfiguring(DbContextOptionsBuilder options)
         => options.UseSqlite("Data Source=DBFileName.db");
    
    Run Code Online (Sandbox Code Playgroud)
  4. 运行迁移命令以开始使用它

     PM> add-migration <MigrationName>  //Ex: add-migration IntialMigration
     PM> update-database
    
    Run Code Online (Sandbox Code Playgroud)

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

本文提供了将 SQLite 与 Asp.net core 3.1 结合使用的简单步骤