EFCore3.1框架的学习和简单使用(一)

1 篇文章 0 订阅

今天学习的是写代码然后将数据迁移到SQLServer数据库当中。
首先建立一个空白的解决方案项目,我在VS2019建立了如下的项目结构:

在这里插入图片描述

在Demo.Data中我从Nuget包管理器中下载了如下的包:

在这里插入图片描述

由于在这之中存存在着许多依赖项,所以下载一个包也会有许多其它的包被下载。然后是在Demo.Domain中我建立了三个个Model,这三个Model会作为一个表的映射关系。在Demo.Data新建类DemoContext:

using Demo.Domain;
using Microsoft.EntityFrameworkCore;

namespace Demo.Data
{

    public class DemoContext:DbContext//这个继承EF框架中的DbContext
    {
        /// <summary>
        /// 在这里重写OnConfiguring的方法来配置数据库的连接字符串
        /// </summary>
        /// <param name="optionsBuilder"></param>
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer("Data Source=.; Initial Catalog=Demo;User Id=sa;Password=123456");
        }

        public DbSet<Club> Clubs { get; set; }//一个实体代表着一张表,暴露成Dbset的这种属性
        public DbSet<League> Leagues { get; set; }
        public DbSet<Player> Players { get; set; }
    }
}

数据库的连接字符串根据自己的需要灵活变换。 在所有的准备工作完成后开始下一步。 打开程序包管理控制台:

在这里插入图片描述

在这里输入get-help entityframework可以得到许多帮助。 在得到的帮助中其实用的到的命令不是很对,主要命令是如下两个:

Add-Migration Adds a new migration.
Update-Database Updates the database to a specified migration.

我们在控制台输入Add-Migration 在其后面增加一个参数,即我需要增加的Migration文件的名称,这个名称是可以自己随意取,我的如下:
在这里插入图片描述

很明显我这里在增加Migration文件的时候它报错了,错误的原因是:它说我这个项目EFDemo它是没有引用Microsoft.EntityFrameworkCore.Design这个库,没有的话那就去NuGet我给它加上

打开EFDEMO的NuGet包管理器,加入Microsoft.EntityFrameworkCore.Design

在这里插入图片描述

点击安装然后再次执行之前的那个命令

在这里插入图片描述

可以看见这个已经执行成功啦。生成了一个Migration的迁移文件。

在这里插入图片描述

在这里有着一个文件夹和两个类,一个类是一个本地的时间戳加上一个在创建Migration迁移文件的时候自己取得文件。
还有一个类叫做DemoContextModelSnapshot,这个相当于一个快照,这个文件很重要,不要手动去改!!!EFCore是根据这个快照来追踪所有Model的一个状态。

using System;
using Microsoft.EntityFrameworkCore.Migrations;

namespace Demo.Data.Migrations
{
    public partial class Initial : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "Leagues",
                columns: table => new
                {
                    Id = table.Column<int>(type: "int", nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
                    Name = table.Column<string>(type: "nvarchar(max)", nullable: true),
                    Country = table.Column<string>(type: "nvarchar(max)", nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Leagues", x => x.Id);
                });

            migrationBuilder.CreateTable(
                name: "Clubs",
                columns: table => new
                {
                    Id = table.Column<int>(type: "int", nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
                    Name = table.Column<string>(type: "nvarchar(max)", nullable: true),
                    City = table.Column<string>(type: "nvarchar(max)", nullable: true),
                    History = table.Column<string>(type: "nvarchar(max)", nullable: true),
                    DateOfEstalishment = table.Column<DateTime>(type: "datetime2", nullable: false),
                    LeagueId = table.Column<int>(type: "int", nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Clubs", x => x.Id);
                    table.ForeignKey(
                        name: "FK_Clubs_Leagues_LeagueId",
                        column: x => x.LeagueId,
                        principalTable: "Leagues",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Restrict);
                });

            migrationBuilder.CreateTable(
                name: "Players",
                columns: table => new
                {
                    Id = table.Column<int>(type: "int", nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
                    Name = table.Column<string>(type: "nvarchar(max)", nullable: true),
                    DateOfBirtth = table.Column<DateTime>(type: "datetime2", nullable: false),
                    ClubId = table.Column<int>(type: "int", nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Players", x => x.Id);
                    table.ForeignKey(
                        name: "FK_Players_Clubs_ClubId",
                        column: x => x.ClubId,
                        principalTable: "Clubs",
                        principalColumn: "Id",
                        onDelete: ReferentialAction.Restrict);
                });

            migrationBuilder.CreateIndex(
                name: "IX_Clubs_LeagueId",
                table: "Clubs",
                column: "LeagueId");

            migrationBuilder.CreateIndex(
                name: "IX_Players_ClubId",
                table: "Players",
                column: "ClubId");
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "Players");

            migrationBuilder.DropTable(
                name: "Clubs");

            migrationBuilder.DropTable(
                name: "Leagues");
        }
    }
}

在上面这个类中有两个方法一个Up方法,一个Down方法。
Up方法是用于一个数据库的修改
Down是执行出错的时候的一个回滚
然后继续往下:

在这里插入图片描述

在这里的两个脚本文件,
Script-Migration
Generates a SQL script from migrations.

Update-Database
Updates the database to a specified migration.
在两个脚本文件中第一个用于生产环境中生成的SQ语句,在开发环境中一般执行下面的那个语句

执行Update-Database:

在这里插入图片描述

执行完成!!!

在这里插入图片描述

数据库中也有了!!!!!

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值