ASP.Net Core中EntityFrameworkCore根据实体类自动创建数据库

ASP.Net Core中EntityFrameworkCore根据实体类自动创建数据库

EntityFrameworkCore根据实体类自动创建数据库

在平时,我们创建数据库都是直接在数据库中创建一个数据库,然后再去创建表,定义字段,字段类型等。
今天我们就来学习怎么让程序通过一行代码自动去创建数据库。

新建项目

俗话说得好,不管如何,要想让车跑,那么首先你必须要有车,那么我们的程序也一样。

  1. 首先新建Asp.Net Core Web Api 项目。
    解决方案资源管理器
我这边是新建了五个项目,大概的意思是:
Tests > 用于编写单元测试
Application > 用于编写API接口
Core > 程序主入口,用来添加和启动各种服务,中间件,也是程序配置文件所在地。
Infrastructure > 基础接口或者帮助类
Models > 用于存放要生成的各种实体类
  1. 添加NuGet引用
    因为根据我的个人习惯,喜欢给项目分类,所以,对于一些Nuget包的引用,我全部都放在了Infrastructure里面
    2.1 Microsoft.EntityFrameworkCore.SqlServer(我用的 SqlServer 根据自己情况自行引用就行)
    2.2 Microsoft.EntityFrameworkCore
    2.3 Microsoft.EntityFrameworkCore.Design

NuGet引用详情

  1. 使项目支持 dotnet ef 工具以使用Migrations
    3.1 手动修改csproj文件(手动添加是因为在NuGet控制台添加 Microsoft.EntityFrameworkCore.Tools.DotNet 时报错,估计是VS的问题),添加以下配置:
<ItemGroup>
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
</ItemGroup>

手动修改csproj文件

  1. 打开 CMD 命令,cd 到项目目录下(F:\File\Visual Studio Files\FH.Host.API\src\FH.Host.API.Core),执行
dotnet build

结果:

用于 .NET Core 的 Microsoft (R) 生成引擎版本 15.9.20+g88f5fadfbe
版权所有(C) Microsoft Corporation。保留所有权利。

  F:\File\Visual Studio Files\FH.Host.API\src\FH.Host.API.Model\FH.Host.API.Model.csproj 的还原在 50.77 ms 内完成。
  F:\File\Visual Studio Files\FH.Host.API\src\FH.Host.API.Infrastructure\FH.Host.API.Infrastructure.csproj 的还原在 105.17 ms 内完成。
  F:\File\Visual Studio Files\FH.Host.API\src\FH.Host.API.Core\FH.Host.API.Core.csproj 的还原在 105.2 ms 内完成。
  F:\File\Visual Studio Files\FH.Host.API\src\FH.Host.API.Application\FH.Host.API.Application.csproj 的还原在 105.11 ms 内完成。
  FH.Host.API.Model -> F:\File\Visual Studio Files\FH.Host.API\src\FH.Host.API.Core\bin\Debug\netcoreapp2.2\FH.Host.API.Model.dll
  FH.Host.API.Infrastructure -> F:\File\Visual Studio Files\FH.Host.API\src\FH.Host.API.Infrastructure\bin\Debug\netcoreapp2.2\FH.Host.API.Infrastructure.dll
  FH.Host.API.Application -> F:\File\Visual Studio Files\FH.Host.API\src\FH.Host.API.Core\bin\Debug\netcoreapp2.2\FH.Host.API.Application.dll
  FH.Host.API.Core -> F:\File\Visual Studio Files\FH.Host.API\src\FH.Host.API.Core\bin\Debug\netcoreapp2.2\FH.Host.API.Core.dll

已成功生成。
    0 个警告
    0 个错误

已用时间 00:00:04.21

当看到这个结果的时候,就证明成功了。

dotnet build执行结果

  1. 第4步完成后继续执行
dotnet ef

结果:


                     _/\__
               ---==/    \\
         ___  ___   |.    \|\
        | __|| __|  |  )   \\\
        | _| | _|   \_/ |  //|\\
        |___||_|       /   \\\/\\

Entity Framework Core .NET Command-line Tools 2.2.6-servicing-10079

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.

Use "dotnet ef [command] --help" for more information about a command.

可以看见独角兽就说明引用成功了。

dotnet ef执行结果

  1. 创建实例 FangHuaHostDbContext 和相关的实体类
    这里我的实例是创建在 Infrastructure 中的 DB 文件夹中

在这里插入图片描述

FangHuaHostDbContext 中,有一行

AppConfigurtaionService.Configuration["ConnectionStrings:Default"]

这样的代码,是我自己扩展的一个配置文件帮助类,用来访问配置文件中的节点,也是放在 Infrastructure 中的 AppConfigurtaion 文件夹中

在这里插入图片描述

具体代码如下:

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;

namespace FH.Host.API.Infrastructure.AppConfigurtaion
{
    /// <summary>
    /// AppConfigurtaion服务
    /// 读取 appsettings.json 文件节点内容
    /// 读取一级节点配置 AppConfigurtaionServices.Configuration["ServiceUrl"];
    /// 读取二级子节点配置 AppConfigurtaionServices.Configuration["Appsettings:SystemName"];
    /// </summary>
    public class AppConfigurtaionService
    {
        public static IConfiguration Configuration { get; set; }

        static AppConfigurtaionService()
        {
            Configuration = new ConfigurationBuilder()
                .Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true })
                .Build();
        }
    }
}

关于 EntityFrameWorkCore 迁移,添加初始化种子数据,也就是默认建表数据的方法:
是在 FangHuaHostDbContext 中重写 OnModelCreating 方法。
FangHuaHostDbContext.cs 中的实体类,我就不展示了,我的是新建在 Model 中的。

最终,FangHuaHostDbContext.cs 中的代码如下:

using FH.Host.API.Infrastructure.AppConfigurtaion;
using FH.Host.API.Model.DefaultEntity;
using Microsoft.EntityFrameworkCore;

namespace FH.Host.API.Infrastructure.DB
{
    public class FangHuaHostDbContext : DbContext
    {
        public FangHuaHostDbContext(DbContextOptions<FangHuaHostDbContext> options)
            : base(options)
        {
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
        	// 连接数据库
            optionsBuilder.UseSqlServer(
            	// 拿到数据库连接字符串,这里我是配置在 “appsettings.json” 文件中
            	/*
	             * “appsettings.json” 文件中的数据库连接字符串:
	             * 
		              // DB连接字符串
					  "ConnectionStrings": {
					    "Default": "Data Source=(IP地址); Initial Catalog=(数据库名); User ID=(Sql账号);Password=(Sql密码);",
					  },
				  */
                AppConfigurtaionService.Configuration["ConnectionStrings:Default"]);
        }

        /// <summary>
        /// 数据初始化
        /// </summary>
        /// <param name="modelBuilder"></param>
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
        	// 这里用来需要需要初始化的种子数据,注意,如果主键是自动生成的,从1开始,慢慢往后加,初始化的时候需要。
            modelBuilder.Entity<FH_Admin>().HasData(
                new FH_Admin { Id = 1, AdminName = "Admin", AdminPwd = "123456" });

            modelBuilder.Entity<FH_Users>().HasData(
                new FH_Users { Id = 1, UserName = "Admin", UserPwd = "123456" });
        }
        
		// 这里是用来添加表的,函数名字,就是你数据库中的表名,而不是取决于你的实体类名
        public DbSet<FH_Admin> FH_Admin { get; set; }

        public DbSet<FH_Users> FH_Users { get; set; }
    }
}
  1. Startup.cs 中将 FangHuaHostDbContext 注册为服务
services.AddDbContext<FangHuaHostDbContext>();

在这里插入图片描述

  1. 使用 Migrations 新建数据库初始化类 DbInitializer
    这里我把 DbInitializer.cs 也放在了和 FangHuaHostDbContext.cs 一样,在同一个文件夹 DB 文件夹中。
using Microsoft.EntityFrameworkCore;

namespace FH.Host.API.Infrastructure.DB
{
    public class DbInitializer
    {
        public void InitializeAsync(FangHuaHostDbContext context)
        {
            // 根据Migrations修改/创建数据库
            context.Database.MigrateAsync();
        }
    }
}
  1. Startup.cs 中的 Configure 方法中,添加参数 FangHuaHostDbContext,.Net Core会使用 DI(依赖注入)FangHuaHostDbContext 注入到 Configure 方法,并添加对 DbInitializer.cs 的调用
public void Configure(IApplicationBuilder app, IHostingEnvironment env, FangHuaHostDbContext context)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            // 根据Migrations修改/创建数据库
            new DbInitializer().InitializeAsync(context);
		}

在这里插入图片描述

10.使用 dotent ef 命令创建 Migrations

在这里插入图片描述
注意:执行命令之前在控制台“默认项目”列表选中DbContext所在的类库,不然会引发报错,导致不能正常执行。

dotnet ef migrations add Initial

Initial 随便命名

如果执行 dotnet ef migrations add Initial 报错:

PM> dotnet ef migrations add Initial
No project was found. Change the current working directory or use the --project option.

在这里插入图片描述

解决办法,执行下面代码,定位到 csproject

dotnet ef migrations script --verbose -i --project "F:\File\Visual Studio Files\FH.Host.API\src\FH.Host.API.Core"

F:\File\Visual Studio Files\FH.Host.API\src\FH.Host.API.Core 是你启动项目所在的文件路径

在这里插入图片描述

完了使用下面的命令取创建

PM> Add-Migration Initial

等程序执行完成后,会在你 DB 文件夹所在的目录下面,创建一个新的文件夹 Migrations
在这里插入图片描述

看到这些文件,就证明我们离成功就差最后一步了。

最后在执行以下代码

PM> Update-Database

然后,你就可以在数据中,看到你创建的数据库和表了。

  1. 更新数据库
    如果你修改了某一个字段,或者添加了某一张新表,只需要执行两个命令,就可以使数据库更新
PM> Add-Migration Initial_Add_Table

这里 Initial_Add_Table 根据你个人喜好自行命名

PM> Update-Database

OK,执行完这两个命令,数据库中的表或者字段就更新了~

今天的学习就到这里吧~

当你的能力还不足以撑不起你的野心时,你就需要静下心来 好好学习。

When your abilities are not enough to support your ambitions, you need to calm down and study hard.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值