ASP.NET Core 设置和初始化数据库 - ASP.NET Core 基础教程 - 简单教程,简单编程

简介: 原文:ASP.NET Core 设置和初始化数据库 - ASP.NET Core 基础教程 - 简单教程,简单编程 ASP.NET Core 设置和初始化数据库 上一章节中我们已经设置和配置好了 EF 框架服务,本章节我们就来学习如何使用 EF 框架设置和初始化数据库 初始化数据库...

原文:ASP.NET Core 设置和初始化数据库 - ASP.NET Core 基础教程 - 简单教程,简单编程

ASP.NET Core 设置和初始化数据库

上一章节中我们已经设置和配置好了 EF 框架服务,本章节我们就来学习如何使用 EF 框架设置和初始化数据库

初始化数据库

初始化数据库的方法之一是使用 EF 框架来创建数据库,仅仅需要两步就能完成

  1. 第一步,给我们的 HelloWorld 项目添加迁移 ( migration ) 代码

    迁移代码是 C# 代码,用来在数据库系统中创建数据库

    当然了,EF 框架可以自动帮我们生成迁移代码

    EF 框架通过对比数据库和我们的模型,并计算出所需的数据库表的更改

    当我们添加其它的模型或对现有模型进行更改 ( 如 Employee 类 )时,我们可以使用 EF 框架创建新的迁移来保持我们的数据库表同步

  2. 第二步,执行迁移代码,更新数据库,也就是说,我们需要明确地应用这些迁移来更新数据库

这两步任务都可以通过在 控制台窗口 ( 终端或 Power Shell 或 命令提示符 ) 中使用一些简单的命令来实现

好吧,开始吧

  1. 首先打开 控制台窗口 ( 终端或 Power Shell 或 命令提示符 ),定位到我们的 HelloWorld 项目下

    $ cd ~/Developer/aspnetcore/HelloWorld/HelloWorld
    

    我用的是 macOS,且我的 HelloWorld 保存在 ~/Developer/aspnetcore/HelloWorld/HelloWorld

    然后使用 ls 命名就可以列出当前目录下的所有文件和子目录

    $ ls
    AppSettings.json  Controllers  HelloWorld.csproj  Models  Program.cs  Properties  Startup.cs  Views  bin  obj  wwwroot
    

    如果你使用的是 Windows,且使用的不是 Power Shell,那么你应该使用 dir 命令而不是 ls 命令

    如果能看到 HelloWorld.csproj 则说明处于正确的目录,否则你应该继续 cd 到该目录下

  2. 然后可以运行下列命令创建迁移代码

    dotnet ef migrations add InitialCreate -v
    
    参数 说明
    dotnet 是 .NET 框架所有命令的开始标识
    ef 是指使用 Entity Framework 提供的命令
    migrations 是指使用迁移命令
    add 是指添加迁移
    InitialCreate 是本次迁移的说明,你可以改成任意文本,但我们推荐最好是能清楚的描述本次迁移的意图
    -v 参数用于输出创建迁移代码时的运行日志,方便出错时我们可以查看错在哪里

    运行失败... 你知道有多坑吗,我写这个教程的时候才 2.1.0,写到一半变成了 2.1.1 了

    运行结果如下

    $ dotnet ef migrations add InitialCreate -v
    Using project '/Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/HelloWorld.csproj'.
    Using startup project '/Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/HelloWorld.csproj'.
    Writing '/Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/obj/HelloWorld.csproj.EntityFrameworkCore.targets'...
    dotnet msbuild /target:GetEFProjectMetadata /property:EFProjectMetadataFile=/var/folders/yk/2446sljj6hn82nvzkdgxltmw0000gn/T/tmp9Zm0P4.tmp /verbosity:quiet /nologo /Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/HelloWorld.csproj
    Writing '/Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/obj/HelloWorld.csproj.EntityFrameworkCore.targets'...
    dotnet msbuild /target:GetEFProjectMetadata /property:EFProjectMetadataFile=/var/folders/yk/2446sljj6hn82nvzkdgxltmw0000gn/T/tmpQa9wxL.tmp /verbosity:quiet /nologo /Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/HelloWorld.csproj dotnet build /Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/HelloWorld.csproj /verbosity:quiet /nologo Build succeeded. 0 Warning(s) 0 Error(s) Time Elapsed 00:00:05.31 dotnet exec --depsfile /Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/bin/Debug/netcoreapp2.1/HelloWorld.deps.json --additionalprobingpath /Users/yufei/.nuget/packages --additionalprobingpath /usr/local/share/dotnet/sdk/NuGetFallbackFolder --runtimeconfig /Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/bin/Debug/netcoreapp2.1/HelloWorld.runtimeconfig.json /usr/local/share/dotnet/sdk/2.1.301/DotnetTools/dotnet-ef/2.1.1/tools/netcoreapp2.1/any/tools/netcoreapp2.0/any/ef.dll migrations add InitialCreate --assembly /Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/bin/Debug/netcoreapp2.1/HelloWorld.dll --startup-assembly /Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/bin/Debug/netcoreapp2.1/HelloWorld.dll --project-dir /Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/ --language C# --working-dir /Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld --verbose --root-namespace HelloWorld Using assembly 'HelloWorld'. Using startup assembly 'HelloWorld'. Using application base '/Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/bin/Debug/netcoreapp2.1'. Using working directory '/Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld'. Using root namespace 'HelloWorld'. Using project directory '/Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/'. Finding DbContext classes... Finding IDesignTimeDbContextFactory implementations... Finding application service provider... Finding IWebHost accessor... Using environment 'Development'. Using application service provider from IWebHost accessor on 'Program'. Found DbContext 'HelloWorldDBContext'. Finding DbContext classes in the project... Using context 'HelloWorldDBContext'. info: Microsoft.EntityFrameworkCore.Infrastructure[10403] Entity Framework Core 2.1.1-rtm-30846 initialized 'HelloWorldDBContext' using provider 'Microsoft.EntityFrameworkCore.Sqlite' with options: None Finding design-time services for provider 'Microsoft.EntityFrameworkCore.Sqlite'... Using design-time services from provider 'Microsoft.EntityFrameworkCore.Sqlite'. Finding design-time services referenced by assembly 'HelloWorld'. No referenced design-time services were found. Finding IDesignTimeServices implementations in assembly 'HelloWorld'... No design-time services were found. Writing migration to '/Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/Migrations/20180623011047_InitialCreate.cs'. Writing model snapshot to '/Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/Migrations/HelloWorldDBContextModelSnapshot.cs'. Done. To undo this action, use 'ef migrations remove' 

    大概意思就是经过漫长的岁月,成功创建了迁移代码

    这一步非常容易出错,如果你有任何错误,欢迎你在讨论区留下你包括的意见

    ASP.NET Core 讨论区

  3. 创建迁移成功后,我们就可以使用下面的命令查看当前有多少迁移代码和它们的状态

    $ dotnet ef migrations list
    

    运行结果如下

    $ dotnet ef migrations list                
    info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
    Entity Framework Core 2.1.1-rtm-30846 initialized 'HelloWorldDBContext' using provider 'Microsoft.EntityFrameworkCore.Sqlite' with options: None 20180623011249_InitialCreate 

    可以看到总共有一个迁移代码,那就是 20180623011249_InitialCreate

    在解决方案管理器中我们还可以看到多出了一个目录 Migrations 和多个文件

  4. 接下来我们就要开始应用这些迁移来更新数据库,执行下面的命令来应用迁移代码

    $ dotnet ef database update -v
    
    参数 说明
    dotnet 是 .NET 框架所有命令的开始标识
    ef 是指使用 Entity Framework 提供的命令
    database 是指使用数据库相关命令
    update 是指更新数据库
    -v 参数用于输出创建迁移代码时的运行日志,方便出错时我们可以查看错在哪里

    执行以上命令,输出结果如下

    $ dotnet ef database update -v
    Using project '/Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/HelloWorld.csproj'.
    Using startup project '/Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/HelloWorld.csproj'.
    Writing '/Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/obj/HelloWorld.csproj.EntityFrameworkCore.targets'...
    dotnet msbuild /target:GetEFProjectMetadata /property:EFProjectMetadataFile=/var/folders/yk/2446sljj6hn82nvzkdgxltmw0000gn/T/tmpDJ7JJ2.tmp /verbosity:quiet /nologo /Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/HelloWorld.csproj
    Writing '/Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/obj/HelloWorld.csproj.EntityFrameworkCore.targets'...
    dotnet msbuild /target:GetEFProjectMetadata /property:EFProjectMetadataFile=/var/folders/yk/2446sljj6hn82nvzkdgxltmw0000gn/T/tmpjmGX4s.tmp /verbosity:quiet /nologo /Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/HelloWorld.csproj dotnet build /Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/HelloWorld.csproj /verbosity:quiet /nologo Build succeeded. 0 Warning(s) 0 Error(s) Time Elapsed 00:00:04.26 dotnet exec --depsfile /Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/bin/Debug/netcoreapp2.1/HelloWorld.deps.json --additionalprobingpath /Users/yufei/.nuget/packages --additionalprobingpath /usr/local/share/dotnet/sdk/NuGetFallbackFolder --runtimeconfig /Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/bin/Debug/netcoreapp2.1/HelloWorld.runtimeconfig.json /usr/local/share/dotnet/sdk/2.1.301/DotnetTools/dotnet-ef/2.1.1/tools/netcoreapp2.1/any/tools/netcoreapp2.0/any/ef.dll database update --assembly /Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/bin/Debug/netcoreapp2.1/HelloWorld.dll --startup-assembly /Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/bin/Debug/netcoreapp2.1/HelloWorld.dll --project-dir /Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/ --language C# --working-dir /Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld --verbose --root-namespace HelloWorld Using assembly 'HelloWorld'. Using startup assembly 'HelloWorld'. Using application base '/Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/bin/Debug/netcoreapp2.1'. Using working directory '/Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld'. Using root namespace 'HelloWorld'. Using project directory '/Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/'. Finding DbContext classes... Finding IDesignTimeDbContextFactory implementations... Finding application service provider... Finding IWebHost accessor... Using environment 'Development'. Using application service provider from IWebHost accessor on 'Program'. Found DbContext 'HelloWorldDBContext'. Finding DbContext classes in the project... Using context 'HelloWorldDBContext'. info: Microsoft.EntityFrameworkCore.Infrastructure[10403] Entity Framework Core 2.1.1-rtm-30846 initialized 'HelloWorldDBContext' using provider 'Microsoft.EntityFrameworkCore.Sqlite' with options: None Finding design-time services for provider 'Microsoft.EntityFrameworkCore.Sqlite'... Using design-time services from provider 'Microsoft.EntityFrameworkCore.Sqlite'. Finding design-time services referenced by assembly 'HelloWorld'. No referenced design-time services were found. Finding IDesignTimeServices implementations in assembly 'HelloWorld'... No design-time services were found. info: Microsoft.EntityFrameworkCore.Database.Command[20101] Executed DbCommand (28ms) [Parameters=[], CommandType='Text', CommandTimeout='30'] PRAGMA foreign_keys=ON; Executed DbCommand (28ms) [Parameters=[], CommandType='Text', CommandTimeout='30'] PRAGMA foreign_keys=ON; info: Microsoft.EntityFrameworkCore.Database.Command[20101] Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30'] PRAGMA foreign_keys=ON; Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30'] PRAGMA foreign_keys=ON; info: Microsoft.EntityFrameworkCore.Database.Command[20101] Executed DbCommand (7ms) [Parameters=[], CommandType='Text', CommandTimeout='30'] CREATE TABLE "__EFMigrationsHistory" ( "MigrationId" TEXT NOT NULL CONSTRAINT "PK___EFMigrationsHistory" PRIMARY KEY, "ProductVersion" TEXT NOT NULL ); Executed DbCommand (7ms) [Parameters=[], CommandType='Text', CommandTimeout='30'] CREATE TABLE "__EFMigrationsHistory" ( "MigrationId" TEXT NOT NULL CONSTRAINT "PK___EFMigrationsHistory" PRIMARY KEY, "ProductVersion" TEXT NOT NULL ); info: Microsoft.EntityFrameworkCore.Database.Command[20101] Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30'] PRAGMA foreign_keys=ON; Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30'] PRAGMA foreign_keys=ON; info: Microsoft.EntityFrameworkCore.Database.Command[20101] Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30'] PRAGMA foreign_keys=ON; Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30'] PRAGMA foreign_keys=ON; info: Microsoft.EntityFrameworkCore.Database.Command[20101] Executed DbCommand (8ms) [Parameters=[], CommandType='Text', CommandTimeout='30'] SELECT COUNT(*) FROM "sqlite_master" WHERE "name" = '__EFMigrationsHistory' AND "type" = 'table'; Executed DbCommand (8ms) [Parameters=[], CommandType='Text', CommandTimeout='30'] SELECT COUNT(*) FROM "sqlite_master" WHERE "name" = '__EFMigrationsHistory' AND "type" = 'table'; info: Microsoft.EntityFrameworkCore.Database.Command[20101] Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30'] PRAGMA foreign_keys=ON; Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30'] PRAGMA foreign_keys=ON; info: Microsoft.EntityFrameworkCore.Database.Command[20101] Executed DbCommand (1ms) [Parameters=[], CommandType='Text', CommandTimeout='30'] SELECT "MigrationId", "ProductVersion" FROM "__EFMigrationsHistory" ORDER BY "MigrationId"; Executed DbCommand (1ms) [Parameters=[], CommandType='Text', CommandTimeout='30'] SELECT "MigrationId", "ProductVersion" FROM "__EFMigrationsHistory" ORDER BY "MigrationId"; info: Microsoft.EntityFrameworkCore.Migrations[20402] Applying migration '20180623011249_InitialCreate'. Applying migration '20180623011249_InitialCreate'. info: Microsoft.EntityFrameworkCore.Database.Command[20101] Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30'] PRAGMA foreign_keys=ON; Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30'] PRAGMA foreign_keys=ON; info: Microsoft.EntityFrameworkCore.Database.Command[20101] Executed DbCommand (1ms) [Parameters=[], CommandType='Text', CommandTimeout='30'] CREATE TABLE "Employees" ( "ID" INTEGER NOT NULL CONSTRAINT "PK_Employees" PRIMARY KEY AUTOINCREMENT, "Name" TEXT NULL ); Executed DbCommand (1ms) [Parameters=[], CommandType='Text', CommandTimeout='30'] CREATE TABLE "Employees" ( "ID" INTEGER NOT NULL CONSTRAINT "PK_Employees" PRIMARY KEY AUTOINCREMENT, "Name" TEXT NULL ); info: Microsoft.EntityFrameworkCore.Database.Command[20101] Executed DbCommand (2ms) [Parameters=[], CommandType='Text', CommandTimeout='30'] INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion") VALUES ('20180623011249_InitialCreate', '2.1.1-rtm-30846'); Executed DbCommand (2ms) [Parameters=[], CommandType='Text', CommandTimeout='30'] INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion") VALUES ('20180623011249_InitialCreate', '2.1.1-rtm-30846'); Done. 

    输出日志很长,大概的意思就是执行成功了

  5. 应用迁移代码成功后我们就能在根目录下发现我们的 blogging.db 文件了

    至于它为什么不在前面章节中提到的 bin/Debug 目录下,我也很疑问,算了,不管了

blogging.db

blogging.db 是一个标准的 SQLite3 数据库文件,我们可以使用 SQLite Studio 打开看看

对了,SQLite Studio 是一个跨平台的软件,你可以点击 https://sqlitestudio.pl/index.rvt?act=download 下载它

使用 SQLite Studio 可以看到我们的 blogging.db 中已经有了表 Employees ,且有两个字段

本章到这里就结束了,我本来想给大家介绍下迁移代码的,但这其实已经超出了基础教程的范畴了,算了,以后有空再来讲讲

目录
相关文章
|
2月前
|
存储 开发框架 JSON
ASP.NET Core OData 9 正式发布
【10月更文挑战第8天】Microsoft 在 2024 年 8 月 30 日宣布推出 ASP.NET Core OData 9,此版本与 .NET 8 的 OData 库保持一致,改进了数据编码以符合 OData 规范,并放弃了对旧版 .NET Framework 的支持,仅支持 .NET 8 及更高版本。新版本引入了更快的 JSON 编写器 `System.Text.UTF8JsonWriter`,优化了内存使用和序列化速度。
|
28天前
|
关系型数据库 MySQL Linux
Linux系统如何设置自启动服务在MySQL数据库启动后执行?
【10月更文挑战第25天】Linux系统如何设置自启动服务在MySQL数据库启动后执行?
72 3
|
28天前
|
关系型数据库 MySQL Linux
在 CentOS 7 中通过编译源码方式安装 MySQL 数据库的详细步骤,包括准备工作、下载源码、编译安装、配置 MySQL 服务、登录设置等。
本文介绍了在 CentOS 7 中通过编译源码方式安装 MySQL 数据库的详细步骤,包括准备工作、下载源码、编译安装、配置 MySQL 服务、登录设置等。同时,文章还对比了编译源码安装与使用 RPM 包安装的优缺点,帮助读者根据需求选择最合适的方法。通过具体案例,展示了编译源码安装的灵活性和定制性。
83 2
|
2月前
|
传感器 数据采集 物联网
探索.NET nanoFramework:为嵌入式设备编程的新途径
探索.NET nanoFramework:为嵌入式设备编程的新途
42 7
|
2月前
|
存储 分布式计算 数据库
阿里云国际版设置数据库云分析工作负载的 ClickHouse 版
阿里云国际版设置数据库云分析工作负载的 ClickHouse 版
|
2月前
|
应用服务中间件 数据库
Tomcat 的数据库连接池设置与应用
Tomcat 的数据库连接池设置与应用
44 3
|
2月前
|
关系型数据库 MySQL 数据库
使用Docker部署的MySQL数据库如何设置忽略表名大小写?
【10月更文挑战第1天】使用Docker部署的MySQL数据库如何设置忽略表名大小写?
189 1
|
2月前
|
开发框架 JavaScript 前端开发
一个适用于 ASP.NET Core 的轻量级插件框架
一个适用于 ASP.NET Core 的轻量级插件框架
|
3月前
|
开发框架 前端开发 JavaScript
ASP.NET MVC 教程
ASP.NET 是一个使用 HTML、CSS、JavaScript 和服务器脚本创建网页和网站的开发框架。
43 7
|
3月前
|
存储 开发框架 前端开发
ASP.NET MVC 迅速集成 SignalR
ASP.NET MVC 迅速集成 SignalR
64 0