.net core 实例教程(二)使用Migration工具创建数据库

本文源码下载地址:http://www.80cxy.com/Blog/ResourceView?arId=202403191532545995NAAqJh

系列教程地址:http://www.80cxy.com/Blog/ArticleView?arId=202403191517574161ay3s5V

本文在项目中使用Migration工具创建数据库,主要包括三个方面的内容,一是在SignUp.Domain项目中创建数据库实体类,二是在SignUp.Infrastructure创建数据库实体配置,也就是实体属性与数据库字段的对应关系配置,三是创建DbContext类,数据库连接存放系统环境变量里面。

项目创建了WebApplicationBuilderExtensions类用于写相关配置代码,如数据库连接配置、Swagger、Cors、Redis等配置。以及实体类的一些基类。

 一、包引用

SignUp.Common 项目安装如下包:

Install-Package Swashbuckle.AspNetCore、

Install-Package System.Data.SqlClient

Install-Package AsmResolver.DotNet  -Version 5.0.1

Install-Package Microsoft.EntityFrameworkCore -Version 7.0.3

Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 7.0.3

Install-Package MediatR

SignUp.Infrastructure项目安装如下包:

Install-Package Microsoft.EntityFrameworkCore -Version 7.0.3

Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 7.0.3

Install-Package Microsoft.EntityFrameworkCore.Tools -Version 7.0.3

SignUp.WebApi项目安装如下包:

Install-Package Microsoft.EntityFrameworkCore.Design -Version 7.0.3

二、创建相关实体类

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

public record SysUser : IAggregateRoot

{

    public Guid Id { get; set; }

    /// <summary>

    /// 用户名

    /// </summary>

    public string UserName { get; set; }

    /// <summary>

    /// 用户密码

    /// </summary>

    private string Password;

    /// <summary>

    /// 真实姓名

    /// </summary>

    public string? RealName { get; set; }

    /// <summary>

    /// 用户类型

    /// </summary>

    public string? UserType { get; set; }

    /// <summary>

    /// 角色Id

    /// </summary>

    public Guid? RoleId { get; set; }

    /// <summary>

    /// 角色

    /// </summary>

    public string? RoleName { get; set; }

    /// <summary>

    /// 是否禁用

    /// </summary>

    public bool IsDisable { get; set; }

}

public record SysRole : IAggregateRoot

{

    public Guid Id { get; set; }

    /// <summary>

    /// 角色名称

    /// </summary>

    public string Name { get; set; }

    /// <summary>

    /// 备注

    /// </summary>

    public string? Remark { get; set; }

}

public record SysRoleDetails

{

    public Guid Id { get; set; }

    /// <summary>

    /// 角色Id

    /// </summary>

    public Guid RoleId { get; set; }

    /// <summary>

    /// 菜单Id

    /// </summary>

    public Guid MenuId { get; set; }

}

public record SysMenu :BaseEntity, IAggregateRoot

{

    /// <summary>

    /// 菜单名称

    /// </summary>

    public string Name { get; set; }

    /// <summary>

    /// 菜单分类

    /// </summary>

    public string? Sort { get; set; }

    /// <summary>

    /// 父层Id

    /// </summary>

    public Guid? ParentId { get; set; }

    /// <summary>

    /// 路由权限值

    /// </summary>

    public string? RouterName { get; set; }

    /// <summary>

    /// 菜单级别

    /// </summary>

    public int Level { get; set; }

    /// <summary>

    /// 备注

    /// </summary>

    public string? Remark { get; set; }

    public SysMenu[] Children { get; set; }

}

public record SysConfig : IAggregateRoot

{

    public float Id { get; set; }

    /// <summary>

    /// 名称

    /// </summary>

    public string Name { get; set; }

    /// <summary>

    /// 值

    /// </summary>

    public string Value { get; set; }

}

三、创建实体配置类

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

using Microsoft.EntityFrameworkCore;

using Microsoft.EntityFrameworkCore.Metadata.Builders;

using SignUp.Domain.Entities;

namespace SignUp.Infrastructure.Configs

{

    public class SysMenuConfig : IEntityTypeConfiguration<SysMenu>

    {

        public void Configure(EntityTypeBuilder<SysMenu> builder)

        {

            builder.ToTable("SysMenu");

            builder.HasKey(f => f.Id);

            builder.Property(f => f.Name).HasMaxLength(200).IsUnicode(true);

            builder.Property(f => f.Sort).HasMaxLength(20).IsUnicode(true);

            builder.Property(f => f.Remark).HasMaxLength(400).IsUnicode(true);

            builder.Ignore(f => f.Children);

        }

    }

    public class SysRoleConfig : IEntityTypeConfiguration<SysRole>

    {

        public void Configure(EntityTypeBuilder<SysRole> builder)

        {

            builder.ToTable("SysRole");

            builder.HasKey(f => f.Id);

            builder.Property(f => f.Name).HasMaxLength(200).IsUnicode(true);

            builder.Property(f => f.Remark).HasMaxLength(400).IsUnicode(true);

        }

    }

    public class SysRoleDetailsConfig : IEntityTypeConfiguration<SysRoleDetails>

    {

        public void Configure(EntityTypeBuilder<SysRoleDetails> builder)

        {

            builder.ToTable("SysRoleDetails");

            builder.HasKey(f => f.Id);

        }

    }

    public class SysMenuConfig : IEntityTypeConfiguration<SysMenu>

    {

        public void Configure(EntityTypeBuilder<SysMenu> builder)

        {

            builder.ToTable("SysMenu");

            builder.HasKey(f => f.Id);

            builder.Property(f => f.Name).HasMaxLength(200).IsUnicode(true);

            builder.Property(f => f.Sort).HasMaxLength(20).IsUnicode(true);

            builder.Property(f => f.Remark).HasMaxLength(400).IsUnicode(true);

            builder.Ignore(f => f.Children);

        }

    }

}

四、创建DbContext

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

using Microsoft.EntityFrameworkCore;

using SignUp.Domain.Entities;

using System.Reflection;

namespace SignUp.Infrastructure

{

    public class SignUpDbContext : DbContext

    {

        public DbSet<RecruitBase> RecruitBase { get; set; }

        public DbSet<RecruitPosition> RecruitPosition { get; set; }

        public DbSet<RecruitUser> RecruitUser { get; set; }

        public DbSet<TalentBase> TalentBase { get; set; }

        public DbSet<TalentBaseCheck> TalentBaseCheck { get; set; }

        public DbSet<TalentEnterviewTicket> TalentEnterviewTicket { get; set; }

        public DbSet<TalentWrittenTicket> TalentWrittenTicket { get; set; }

        public DbSet<SysLog> SysLog { get; set; }

        public DbSet<SysMenu> SysMenu { get; set; }

        public DbSet<SysUser> SysUser { get; set; }

        public DbSet<SysRole> SysRole { get; set; }

        public DbSet<SysRoleDetails> SysRoleDetails { get; set; }

        public DbSet<TalentFile> TalentFile { get; set; }

        public SignUpDbContext(DbContextOptions<SignUpDbContext> opt) : base(opt)

        {

        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)

        {

            base.OnModelCreating(modelBuilder);

            modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());

        }

    }

}

五、创建DbContextFactory类供Migration工具操作数据库使用

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

using Microsoft.EntityFrameworkCore;

using Microsoft.EntityFrameworkCore.Design;

using Microsoft.Extensions.Configuration;

namespace SignUp.Infrastructure

{

    //migration操作数据库使用

    public class DbContextFactory : IDesignTimeDbContextFactory<SignUpDbContext>

    {

        public SignUpDbContext CreateDbContext(string[] args)

        {

            var builder = new DbContextOptionsBuilder<SignUpDbContext>();

            //从appsettings.json获取数据库连接

            //IConfigurationRoot configuration = new ConfigurationBuilder()

            //    .SetBasePath(Directory.GetCurrentDirectory())

            //    .AddJsonFile("appsettings.json")

            //    .Build();

            //string connStr = configuration.GetValue<string>("DefaultDB:ConnStr");

            //从环境变量里面获取数据库连接

            IConfigurationRoot configuration = new ConfigurationBuilder().AddEnvironmentVariables().Build();

            string connStr = configuration.GetValue<string>("DefaultDB:ConnStr");

            builder.UseSqlServer(connStr);

            return new SignUpDbContext(builder.Options);

        }

    }

}

六、执行Migration命令创建数据库

Add-Migration init

Update-database

附:WebApplicationBuilderExtensions源码

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

using Microsoft.AspNetCore.Builder;

using Microsoft.EntityFrameworkCore;

using Microsoft.Extensions.Configuration;

using Microsoft.Extensions.DependencyInjection;

using SignUp.Common.Commons;

using SignUp.Common.EFCore;

using SignUp.Common.EFCore.DBConfiguration;

using System.Data.SqlClient;

namespace SignUp.Common.Initializer

{

    public static class WebApplicationBuilderExtensions

    {

        public static void ConfigureDbConfiguration(this WebApplicationBuilder builder)

        {

            //从数据库中读取相关配置信息,如Redis链接

            builder.Host.ConfigureAppConfiguration((hostCtx, configBuilder) =>

            {

                //不能使用ConfigureAppConfiguration中的configBuilder去读取配置,否则就循环调用了,因此这里直接自己去读取配置文件

                //读取appsettings.json文件配置

                //var configRoot = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();

                //string connStr = configRoot.GetValue<string>("DefaultDB:ConnStr");

                //读取环境变量配置

                //string connStr = builder.Configuration.GetValue<string>("DefaultDB:ConnStr");

                //configBuilder.AddDbConfiguration(() => new SqlConnection(connStr), reloadOnChange: true, reloadInterval: TimeSpan.FromSeconds(5));

            });

        }

        public static void ConfigureExtraServices(this WebApplicationBuilder builder, InitializerOptions initOptions)

        {

            IServiceCollection services = builder.Services;

            IConfiguration configuration = builder.Configuration;

            var assemblies = ReflectionHelper.GetAllReferencedAssemblies();

            //配置数据库链接

            services.AddAllDbContexts(ctx =>

            {

                //连接字符串如果放到appsettings.json中,会有泄密的风险

                //如果放到UserSecrets中,每个项目都要配置,很麻烦

                //因此这里推荐放到环境变量中。

                string connStr = configuration.GetValue<string>("DefaultDB:ConnStr");

                ctx.UseSqlServer(connStr);

            }, assemblies);

        }

    }

}

项目解决方案截图如下:

学习交流

附:.net core 实例教程(二)使用Migration工具创建数据库

  • 24
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Laravel 使用 Migration 来创建和管理数据库表,使得数据库的管理变得更加简单和高效。 以下是使用 Migration 在 Laravel 中创建数据库表的步骤: 1. 首先,在命令行中使用 `php artisan make:migration` 命令创建一个 Migration 文件,命令格式如下: ``` php artisan make:migration create_table_name --create=table_name ``` 其中,`create_table_name` 是 Migration 文件名,`table_name` 是要创建的数据库表名。 2. 接着,打开刚刚创建的 Migration 文件,可以看到该文件包含了两个函数:`up()` 和 `down()`。 `up()` 函数用于定义创建数据库表的操作,`down()` 函数用于定义回滚操作。 3. 在 `up()` 函数中,使用 Laravel 提供的 Schema 构建器来定义数据库表的结构,例如: ``` public function up() { Schema::create('users', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('name'); $table->string('email')->unique(); $table->string('password'); $table->timestamps(); }); } ``` 上述代码创建了一个名为 `users` 的数据库表,包含 `id`、`name`、`email`、`password` 和 `timestamps` 等字段。 4. 最后,在命令行中使用 `php artisan migrate` 命令将 Migration 文件中定义的数据库表结构应用到数据库中,命令格式如下: ``` php artisan migrate ``` 执行成功后,可以在数据库中看到新创建的 `users` 数据库表。 以上就是使用 Migration 在 Laravel 中创建数据库表的步骤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值