从零开始手把手教你,.net 6用EF Core基本创建表,迁移到SQL Server数据库

25 篇文章 7 订阅
4 篇文章 0 订阅

前言:

用到的迁移命令:
Add-Migration test 生成迁移文件命令,test是迁移文件名称
Update-Database 迁移更新到数据库
用到的NuGet包
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Tools
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Design

一.创建项目,安装需要依赖包

在这里插入图片描述
在这里插入图片描述
创建完成后安装NuGet包
在这里插入图片描述
搜索安装
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Tools
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Design
在这里插入图片描述

二. 创建表实体类和上下文类
  1. 创建Context文件夹并创建两个类,一个表实体类City,一个用于绑定上下文类DemoContext
    在这里插入图片描述
  2. City表类添加几个字段,全部代码如下
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace WebApplication1.Context
{
    public class City
    {
        [Key]
        public int Id { get; set; }
        [Column(TypeName = "nvarchar(100)")]
        public string Name { get; set; }

        [Column(TypeName = "nvarchar(100)")]
        public string AreaCode { get; set; }
    }
}
  1. 在上下文类DemoContext注册刚才的City表类,全部代码如下
using Microsoft.EntityFrameworkCore;

namespace WebApplication1.Context
{
    public class DemoContext : DbContext
    {

        public DbSet<City> Cities { get; set; }

        public DemoContext(DbContextOptions<DemoContext> option) : base(option)
        {

        }
 
    }
}

在这里插入图片描述

三. 注册服务,连接数据库,开始迁移

1.在appsettings.json添加数据库连接串

 "ConnectionStrings": {
    "DbConnectionString": "Data Source = localhost;Initial Catalog = myDataBasetest;User Id = sa;Password = 123456;"
  }

在这里插入图片描述2. 在Program注册服务,使用连接配置字符串 连接数据库

builder.Services.AddDbContext<DemoContext>(option =>
{
    string DbConnectionString = builder.Configuration.GetConnectionString("DbConnectionString");
    option.UseSqlServer(DbConnectionString);
});

在这里插入图片描述
3. 打开程序包管理器控制台,使用命令Add-Migration test生成迁移文件,准备开始迁移
在这里插入图片描述
test是迁移文件名称
在这里插入图片描述
生成迁移文件成功后可以查看
在这里插入图片描述
4.使用Update-Database 命令开始迁移,更新表实体类到数据库
在这里插入图片描述
查看数据库,迁移成功
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值