当前位置:Gxlcms > 数据库问题 > (17)ASP.NET Core EF基于数据模型创建数据库

(17)ASP.NET Core EF基于数据模型创建数据库

时间:2021-07-01 10:21:17 帮助过:12人阅读

mvc -n MyCoreWeb

更改为项目目录,你输入的下一个命令需要针对新项目运行:

cd MyCoreWeb

3.安装Entity Framework Core

要安装EF Core,请为要作为目标对象的EF Core数据库提供程序安装程序包。有关可用提供程序的列表,请参阅数据库提供程序。因为我本机是用SqlServer数据库,所以可以通过以下两种方式安装EF Core。

3.1在包管理器控制台输入命令来安装程序包(“工具”>“NuGet包管理器”>“程序包管理器控制台”)

install-package Microsoft.EntityFrameworkCore.SqlServer -Version 2.2.0

3.2通过在CLI输入命令行来安装程序包

--更改为项目所在目录
cd /d D:\Project\MyCoreWeb
--输入CLI命令安装程序包
dotnet add package Microsoft.EntityFrameworkCore.SqlServer

4.创建模型

在Models文件夹下创建BloggingContext.cs文件,为了简单起见,我们都将Blog、Post实体代码写在BloggingContext.cs文件中:

public class BloggingContext : DbContext
{
    public BloggingContext(DbContextOptions<BloggingContext> options): base(options){ }
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }
}
public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
    public ICollection<Post> Posts { get; set; }
}
public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
    public int BlogId { get; set; }
    public Blog Blog { get; set; }
}

5.使用依赖注入注册上下文

在应用程序启动过程中,通过依赖关系注入注册服务(如 BloggingContext),以便能够通过构造函数的参数和属性向使用服务的组件(如 MVC 控制器)自动提供该服务。如果想要在MVC控制器里面调用BloggingContext.cs,那么就要在Startup.cs中将其注册为服务。

public void ConfigureServices(IServiceCollection services)
{
    var connection = @"Server=.;Database=Blogging;Trusted_Connection=True;ConnectRetryCount=0";
    services.AddDbContext<BloggingContext>(options => options.UseSqlServer(connection));
}

为简单起见,这里把连接字符串直接在代码中定义。但是通常是会将连接字符串放在配置文件或环境变量中。例如:

appsettings.json
{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "BloggingDatabase": "Server=.;Database=Blogging;Trusted_Connection=True;"
  }
} 

Startup.cs中其注册的服务代码为:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<BloggingContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("BloggingDatabase")));
}

6.迁移创建数据库(重点)

这个章节比较重要,下面让我们来学习下如何迁移创建数据库。

6.1Visual Studio PowerShell手动来创建项目(“工具”>“NuGet包管理器”>“程序包管理器控制台”)

Add-Migration InitialCreate
Update-Database

如果收到错误,指出The term ‘add-migration‘ is not recognized as the name of a cmdlet,请关闭并重新打开Visual Studio。
Add-Migration命令为迁移搭建基架,以便为模型创建一组初始表。Update-Database命令创建数据库并向其应用程序新的迁移。
因为程序包管理器不支持PowerShell 2.0版本的迁移,需要升级到3.0版本,所以这里就暂时演示不了,请大家自行升级3.0或以上版本测试。
技术图片

6.2通过在CLI输入命令行来迁移

--更改为项目所在目录
cd /d D:\Project\MyCoreWeb
--迁移搭建基架
dotnet ef migrations add InitialCreate
--创建数据库并向其应用程序新的迁移
dotnet ef database update

下面我们来看看迁移创建数据库效果:

技术图片

技术图片

技术图片


参考文献:
使用新数据库在ASP.NET Core上开始使用EF Core

(17)ASP.NET Core EF基于数据模型创建数据库

标签:ddb   add   sof   style   管理器   程序   pow   read   col   

人气教程排行