用VisualStudio2017创建了个.NetCore的MVC项目,介绍两种CodeFirst创建数据库方式。
1.Commnd Line Tools cmd命令行
2.Package Manager Console 包管理器
第一种依赖 Microsoft.EntityFrameworkCore.Tools.DotNet 、 Microsoft.EntityFrameworkCore.Design
打开项目所在的文件位置(注意:不是解决方案的位置),win+r , cmd ,cd 到项目所在位置
使用 dotnet ef 命令
Usage: dotnet ef [options] [command]
Options:
--version Show version information
-h|--help Show help information
-v|--verbose Show verbose output.
--no-color Don't colorize output.
--prefix-output Prefix output with level.
Commands:
database Commands to manage the database.
dbcontext Commands to manage DbContext types.
migrations Commands to manage migrations.
dotnet ef migrations add InitialCreate
dotnet ef database update
对于第二种,我们常用的方式,在VisualStudio的程序包管理器中使用迁移命令生成数据库
依赖 Microsoft.EntityFrameworkCore.Tools
对于这些依赖项,可以在包管理器中通过 Install-Package 直接安装,还可以在 Nuget 管理器中安装
然后使用和以前一样的命令
add-migration
update-database
script-migration
官方教程默认是内置的Sql Server对象管理器,在项目的appsetting.json文件中配置的默认连接也是,我改到本地的sql server了
"ConnectionStrings": {
"DefaultConnection": "Server=DESKTOP-2U899KJ(机器名);Initial Catalog=ContosoUniversity;User ID=sa;Password=sasa"
/*"DefaultConnection": "Server=(localdb)\MSSQLLocalDB;Database=ContosoUniversity;Trusted_Connection=True;MultipleActiveResultSets=true"*/
}