Microsoft.EntityFrameworkCore.Sqlite的学习
SQLite in ASP.NET Core with EntityFrameworkCore
ASP.NET Core 2: Using SQLite as a light weight database
Step 1:
Create your application.

Step 2:
Get the necessary packages
Microsoft.EntityFrameworkCore 1.0.0
Microsoft.EntityFrameworkCore.SQlite 1.0.0
Step 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:
Add your context to your services:
(Located in your Startup class)
public void ConfigureServices(IServiceCollection services)
{
services.AddEntityFrameworkSqlite().AddDbContext<DatabaseContext>();
}
Step 5:
Create your database on startup, by adding it to the startup method
(Located in the Startup class)
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.
The old guide still applies regarding how you create your models as well as using your database context.
Step 1:
Create your ASP.NET web application

Step 2:
Go to Tools -> Nuget Packet Manager -> Manage Nuget Packages for Solution.
Search for EntityFramework.SQLite and check the Include prelease box.
Install the package

Step 3: Creating a context
Create a context class for your database.
Call it whatever you want, but let's go with something that's customiary, like MyDbContext.
Make your new class inherit the DbContext class and override the OnConfiguring method and define your connection like so:
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:
Go to the Startup.cs and make sure your database is created at the start of your web application:
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
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!)
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
Go to your HomeController and add a new field to your controller.
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)
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:

The second line is (or would be) the title of our first category in our database.
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.
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
Microsoft.EntityFrameworkCore.Sqlite的学习的更多相关文章
- .NET CORE 学习笔记之安装EF【Microsoft.EntityFrameworkCore】扩展报错
最近在学习.NET CORE ,刚开始就遇到问题了. 安装EF框架的试试就报错, 报错如下: 错误 程序包还原失败.正在回滚“XXX”的程序包更改. 找了好久的方案,网上也没搜到对应的问题和方案,然而 ...
- Android中的SQLite使用学习
Android中的SQLite使用学习 SQLite是非常流行的嵌入式关系型数据库,轻载, 速度快,而且是开源.在Android中,runtime提供SQLite,所以我们可以使用SQLite,而且是 ...
- EF core2.1+MySQL报错'Void Microsoft.EntityFrameworkCore.Storage.Internal.RelationalParameterBuilder..ctor(Microsoft.EntityFrameworkCore.Storage.IRelationalTypeMapper)
一.使用.net core 2.0 EF mysql 运行一直报错如下: An unhandled exception occurred while processing the request. M ...
- Could not load file or assembly 'Microsoft.EntityFrameworkCore.Relational
提示的很明确了,缺少Microsoft.EntityFrameworkCore.Relational引用.nuget安装上即可.
- ASP.NetCore 错误 NU1605 检测到包降级: Microsoft.Data.Sqlite 从 2.2.1 降级到 2.1.0
找到使用的.csproj文件 将 <PackageReference Include="Microsoft.Data.Sqlite" Version="2.1.0& ...
- uwp - 解决“Microsoft.EntityFrameworkCore.Tools –Pre因为在此系统上禁止运行脚本”
在uwp使用ef时,需要安装“Microsoft.EntityFrameworkCore.Tools –Pre” ,如果安装失败提示:“无法加载文件 \.nuget\packages\Microsof ...
- UWP使用Microsoft.Data.Sqlite的记录
我在UWP中使用SQLite数据库时,并没有使用网上的SQLite for Universal App Platform方案,而使用了Microsoft和SQLite社区一起维护的Microsoft. ...
- 引用Nuget包Microsoft.EntityFrameworkCore.Tools.DotNet报错
错误如下 解决方法 使用VS2017或更高版本在改项目右键,选择“编辑xxx.csproj”,并添加如下一句话,就可以成功引用改Nuget包 <PackageReference Include= ...
- Microsoft.EntityFrameworkCore.Tools 相关命令
一.前言 Entity Framework(后面简称EF)作为微软家的ORM,自然而然从.NET Framework延续到了.NET Core. 二.程序包管理器控制台 为了能够在控制台中使用命令行来 ...
随机推荐
- elsearch
1. ElasticSearch是性能优化的分布式全文搜索引擎,存储数据的载体是文档(Document),它的优势在于搜索速度快和支持聚合操作,在更新文档时,基本上能够达到实时搜索.ElasticSe ...
- Fiddler4入门--手机抓包工具安装和使用说明
Fiddler4入门--手机抓包工具安装和使用说明.电脑最好是笔记本连同一个wifi,这样能和手机保持统一局域网内. 很多区块链dapp项目方风控做的很差,利用fiddler抓包分析找一些漏洞,然后利 ...
- SEO三种职位类型:编辑型SEO、技术型SEO、营销型SEO详解
SEO三种职位类型:编辑型SEO.技术型SEO.营销型SEO详解 网站SEO优化作为营销端的服务之一,这些年也呈现出日新月异的格局.一改过去游兵散将式的小作坊生产模式,不断有力量强大的公司团体加入到这 ...
- linux下postgresql的连接数配置
1.查询当前连接数: select count(*) from pg_stat_activity; 2.查询最大连接数 show max_connections; 3.修改最大连接数 SHOW con ...
- 使用BenchmarkSQL测试PostgreSQL
BenchmarkSQL是一款经典的开源数据库测试工具,内嵌了TPCC测试脚本,可以对EnterpriseDB.PostgreSQL.MySQL.Oracle以及SQL Server等数据库直接进行测 ...
- kubernetes install for centos
官方的文档写的很清楚 https://kubernetes.io/docs/getting-started-guides/centos/centos_manual_config/ 如果已经安装过doc ...
- QRegExp 正则表达式详解
引言 正则表达式(regular expression)就是用一个“字符串”来描述一个特征,然后去验证另一个“字符串”是否符合这个特征.比如 表达式“ab+” 描述的特征是“一个 'a' 和 任意个 ...
- mybatis之关联映射
###mybatis使用之一对一关联映射 1)分析并画ER图.(特别是一对一.一对多.多对多的情况) 2)启动终端数据库,并建库建表,在表中插入值和字段,并查看结果.(后期把navicat用上) 3) ...
- Golang两种执行流程以及区别
Go语言的执行方式有两种,一种是编译后再执行,另一种直接go run执行. 一.先编译后执行 .go文件(源代码)--->go build指令把源代码编译(如果是windows下会编译出一个.e ...
- Codeforces Round #439 (Div. 2) Problem E (Codeforces 869E) - 暴力 - 随机化 - 二维树状数组 - 差分
Adieu l'ami. Koyomi is helping Oshino, an acquaintance of his, to take care of an open space around ...