.net core migrations案例

1.新建一个webApi(MV C)项目

前提:

记得使用Nuget引入依赖

1.Microsoft.EntityFrameWorkCore

2.Microsoft.EntityFrameWorkCore.Design

3.Pemelo.EntityFrameworkCore.Mysql

开始:1.新建一个类

using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace ChainTech.HRP.EPDPedia.Models
{
    [Table("dept")]
    public class Dept
	{
		public Dept()
		{
		}
        [Key]
        [Column("id")]
        [MaxLength(64)]
        public string id { get; set; }

    
        [Column("dept_name")]
        [MaxLength(64)]
        public string deptName { get; set; }


        [Column("addr")]
        [MaxLength(16)]
        public string addr { get; set; }
    }
}

2.新建一个context代码如下

using System;
using Microsoft.EntityFrameworkCore;

namespace ChainTech.HRP.EPDPedia.Database
{
	public class DeptDbContext:DbContext
	{
		public DeptDbContext(DbContextOptions<DeptDbContext> options):base(options)
		{
		}
        public DbSet<Dept> Dept { get; set; }
    }

}

3.在appsettings.json中加入 连接数据库的

   "AllowedHosts": "*",
    "ConnectionStrings": {
        "SourceDbContext": "server=127.0.0.1;UserId=账号;password=你的数据库密码;database=数据库;port=3306;CharSet=utf8;"
    },

4.在statup.cs中的configServices中加入以下代码

services.AddDbContext<SourceDbContext>(options => options.UseMySql(Configuration.GetConnectionString("SourceDbContext"), MySqlServerVersion.LatestSupportedServerVersion));

5.打开控制台

先安装ef工具:dotnet tool install --global dotnet-ef

6.打开当前项目的终端输入

dotnet ef migrations add InitialCreate
注意:add后面的其实是新增的文件的一个名字

7.dotnet ef database update

数据库就多了一张你刚刚那张表和实体类映射的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值