ASP.NET 核心中的 SQLite 与 EntityFrameworkCore
SQLite in ASP.NET Core with EntityFrameworkCore
如何使用 EntityFramework 7 在 ASP.NET 核心 Web 应用程序中添加和使用 SQLite 数据库?
我在听说 ASP.NET Core 并创建了我的第一个 Web 应用程序的那一刻就投入其中,我突然有了一堆我想存储的数据,而 SQLite 似乎是显而易见的选择。
因为我希望它保留在我的应用程序中,所以保持它轻量级、简单并避免设置单独的数据库。
那么如何在 ASP.NET Core 中创建 SQLite 数据库?
- ASP.NET 核心 - 现在以前称为 ASP.NET MVC 6
- EntityFramework 核心 - 现在以前称为 EntityFramework 7
更新:2016 年 11 月 4 日。
重新格式化 - 图片到代码示例。
信息:
请记住,在某些代码示例中,省略了由 visual studio 模板生成的代码。
更新:2016 年 7 月 11 日。
.NET Core 和 EntityFrameWork Core 版本 1.0 即将推出!
所以本指南值得更新
第 2 步:
获取必要的包
Microsoft.EntityFrameworkCore1.0.0
Microsoft.EntityFrameworkCore.SQLite 1.0.0
第 3 步:
创建您的上下文:
(上下文将是您创建的 class)
public class DatabaseContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Filename=MyDatabase.db");
}
}
第 4 步:
将您的上下文添加到您的服务中:
(位于您的 Startup class)
public void ConfigureServices(IServiceCollection services)
{
services.AddEntityFrameworkSqlite().AddDbContext<DatabaseContext>();
}
第 5 步:
通过将其添加到启动方法
,在启动时创建数据库
(位于启动 class)
public Startup(IHostingEnvironment env)
{
using(var client = new DatabaseContext())
{
client.Database.EnsureCreated();
}
}
瞧瞧!
现在您将能够在 ASP.NET 核心应用程序中使用 SQLite。
关于如何创建模型以及使用数据库上下文,旧指南仍然适用。
更新:2016 年 5 月 28 日。
.NET Core RC2 和 EntityFramework Core RC1 已经发布。
他们改进并简化了设置 SQLite 的步骤。
但是由于 Newtonsoft.Json 库和 NuGet 的错误,我遇到了一些问题并且无法复制它。
如果你想这样做,我建议暂时使用 RC1 库!
第 1 步:
创建您的 ASP.NET 网络应用程序
第 2 步:
转到工具 -> Nuget 数据包管理器 -> 管理解决方案的 Nuget 包。
搜索 EntityFramework.SQLite
并选中 Include prelease
框。
安装包
步骤 3:创建上下文
为您的数据库创建上下文 class。
随心所欲地称呼它,但让我们使用一些习惯的东西,比如 MyDbContext
。
让你的新 class 继承 DbContext class 并重写 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
并为每个新模型添加一个新的 属性(假设你想要每个模型都有一个 table!)
这是一个例子:
我的模型:
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);
}
}
第 6 步:使用上下文
转到您的 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,在页面上显示:
第二行是(或将是)我们数据库中第一个类别的标题。
这是我的第一次问答 - 如果您有任何意见或需要澄清的事情,请随时发表评论。
这是一个非常基本的示例,说明如何将 SQLite 数据库实现到 ASP.NET Core MVC Web 应用程序中。
请注意,有几种方法可以设置数据库的连接字符串,如何使用上下文,EntityFramework 7 仍然是预发布
如果您想使用 SQLite 为数据库创建 ASP.NET 核心 Web 应用程序,我强烈建议您使用 Yeoman to scaffold the app for you. 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). You then need to install Node.js which comes with npm and then install the following npm packages: yo and generator-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 restore
、dotnet ef database update
,然后 dotnet run
并转到 localhost:5000
以确保项目是 运行ning。
现在您可以在 Visual Studio 2015(假设您使用的是 Windows)或 Visual Studio 代码中打开项目。
最棒的是 Startup.cs
、project.json
和 appsettings.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
.
要了解有关将 SQLite 数据库与 .NET Core 和 EF Core 结合使用的更多信息,请查看这篇文章:.NET Core - New Database
安装下面提到的包
PM> Install-Package Microsoft.EntityFrameworkCore
PM> Install-Package Microsoft.EntityFrameworkCore.Sqlite
PM> Install-Package Microsoft.EntityFrameworkCore.Tools
创建模型
创建 DBContext class 添加 SQLite 连接配置
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlite("Data Source=DBFileName.db");
运行 开始使用迁移命令
PM> add-migration <MigrationName> //Ex: add-migration IntialMigration
PM> update-database
https://fullstack-lab.co.in/Sqlite-entity-framework-core-quick-start
本文提供了在 Asp.net core 3.1
中使用 SQLite 的简单步骤
在点网 6 中:
您的 DbContext 构造函数应如下所示:(从 DbContext 中删除 OnConfiguring 方法。
public PaymentDbContext(DbContextOptions<PaymentDbContext> options) : base(options)
{
}
并在 program.cs 文件中,像这样添加您的服务:
builder.Services.AddDbContext<PaymentDbContext>(options =>
options.UseSqlite($"Data Source={dbPath}"));
dbPath 是你的数据库地址。
如果您想更新位于不同解决方案中的数据库和 dbContext 文件,请不要忘记在 dotnet ef 数据库更新命令中使用 --startup-project :) 例如:
dotnet ef database update --startup-project ../PaymentProject.Api/PaymentProject.Api.csproj
如何使用 EntityFramework 7 在 ASP.NET 核心 Web 应用程序中添加和使用 SQLite 数据库?
我在听说 ASP.NET Core 并创建了我的第一个 Web 应用程序的那一刻就投入其中,我突然有了一堆我想存储的数据,而 SQLite 似乎是显而易见的选择。
因为我希望它保留在我的应用程序中,所以保持它轻量级、简单并避免设置单独的数据库。
那么如何在 ASP.NET Core 中创建 SQLite 数据库?
- ASP.NET 核心 - 现在以前称为 ASP.NET MVC 6
- EntityFramework 核心 - 现在以前称为 EntityFramework 7
更新:2016 年 11 月 4 日。
重新格式化 - 图片到代码示例。
信息:
请记住,在某些代码示例中,省略了由 visual studio 模板生成的代码。
更新:2016 年 7 月 11 日。
.NET Core 和 EntityFrameWork Core 版本 1.0 即将推出!
所以本指南值得更新
第 2 步:
获取必要的包
Microsoft.EntityFrameworkCore1.0.0
Microsoft.EntityFrameworkCore.SQLite 1.0.0
第 3 步:
创建您的上下文:
(上下文将是您创建的 class)
public class DatabaseContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Filename=MyDatabase.db");
}
}
第 4 步:
将您的上下文添加到您的服务中:
(位于您的 Startup class)
public void ConfigureServices(IServiceCollection services)
{
services.AddEntityFrameworkSqlite().AddDbContext<DatabaseContext>();
}
第 5 步:
通过将其添加到启动方法
,在启动时创建数据库
(位于启动 class)
public Startup(IHostingEnvironment env)
{
using(var client = new DatabaseContext())
{
client.Database.EnsureCreated();
}
}
瞧瞧!
现在您将能够在 ASP.NET 核心应用程序中使用 SQLite。
关于如何创建模型以及使用数据库上下文,旧指南仍然适用。
更新:2016 年 5 月 28 日。
.NET Core RC2 和 EntityFramework Core RC1 已经发布。
他们改进并简化了设置 SQLite 的步骤。
但是由于 Newtonsoft.Json 库和 NuGet 的错误,我遇到了一些问题并且无法复制它。
如果你想这样做,我建议暂时使用 RC1 库!
第 1 步:
创建您的 ASP.NET 网络应用程序
第 2 步:
转到工具 -> Nuget 数据包管理器 -> 管理解决方案的 Nuget 包。
搜索 EntityFramework.SQLite
并选中 Include prelease
框。
安装包
步骤 3:创建上下文
为您的数据库创建上下文 class。
随心所欲地称呼它,但让我们使用一些习惯的东西,比如 MyDbContext
。
让你的新 class 继承 DbContext class 并重写 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
并为每个新模型添加一个新的 属性(假设你想要每个模型都有一个 table!)
这是一个例子:
我的模型:
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);
}
}
第 6 步:使用上下文
转到您的 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,在页面上显示:
第二行是(或将是)我们数据库中第一个类别的标题。
这是我的第一次问答 - 如果您有任何意见或需要澄清的事情,请随时发表评论。
这是一个非常基本的示例,说明如何将 SQLite 数据库实现到 ASP.NET Core MVC Web 应用程序中。
请注意,有几种方法可以设置数据库的连接字符串,如何使用上下文,EntityFramework 7 仍然是预发布
如果您想使用 SQLite 为数据库创建 ASP.NET 核心 Web 应用程序,我强烈建议您使用 Yeoman to scaffold the app for you. 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). You then need to install Node.js which comes with npm and then install the following npm packages: yo and generator-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 restore
、dotnet ef database update
,然后 dotnet run
并转到 localhost:5000
以确保项目是 运行ning。
现在您可以在 Visual Studio 2015(假设您使用的是 Windows)或 Visual Studio 代码中打开项目。
最棒的是 Startup.cs
、project.json
和 appsettings.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
.
要了解有关将 SQLite 数据库与 .NET Core 和 EF Core 结合使用的更多信息,请查看这篇文章:.NET Core - New Database
安装下面提到的包
PM> Install-Package Microsoft.EntityFrameworkCore PM> Install-Package Microsoft.EntityFrameworkCore.Sqlite PM> Install-Package Microsoft.EntityFrameworkCore.Tools
创建模型
创建 DBContext class 添加 SQLite 连接配置
protected override void OnConfiguring(DbContextOptionsBuilder options) => options.UseSqlite("Data Source=DBFileName.db");
运行 开始使用迁移命令
PM> add-migration <MigrationName> //Ex: add-migration IntialMigration PM> update-database
https://fullstack-lab.co.in/Sqlite-entity-framework-core-quick-start
本文提供了在 Asp.net core 3.1
中使用 SQLite 的简单步骤在点网 6 中: 您的 DbContext 构造函数应如下所示:(从 DbContext 中删除 OnConfiguring 方法。
public PaymentDbContext(DbContextOptions<PaymentDbContext> options) : base(options)
{
}
并在 program.cs 文件中,像这样添加您的服务:
builder.Services.AddDbContext<PaymentDbContext>(options =>
options.UseSqlite($"Data Source={dbPath}"));
dbPath 是你的数据库地址。
如果您想更新位于不同解决方案中的数据库和 dbContext 文件,请不要忘记在 dotnet ef 数据库更新命令中使用 --startup-project :) 例如:
dotnet ef database update --startup-project ../PaymentProject.Api/PaymentProject.Api.csproj