从零开始学习ASP.NET CORE(十七)Entity Framework

首先,微软官方文档有对Entity Famework详细的描述和教程
链接: https://learn.microsoft.com/zh-cn/docs/
下面主要讲ASP.NET CORE中的Entity Famework如何部署和使用
.net控制台和winform窗体文件可以参考官方文档
在这里插入图片描述

添加DbContext

新建一个类,继承于DbContext,里面除了构造函数,需要添加DbSet,T是需要连接数据库映射的类

public class AppDbContext : DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
        {
            
        }
        public DbSet<Student> Students { get; set; }
    }

安装程序包

根据自己的数据库,查看官网链接: https://learn.microsoft.com/zh-cn/ef/core/providers/?tabs=dotnet-core-cli,需要安装的NuGet包,需要注意.net的框架版本和包版本对应
在这里插入图片描述

appsettings配置中添加配置信息

{
  ······
  "ConnectionStrings": {
    "MysqlConnectString": "data source=127.0.0.1;port=3306; database=sys;user id=root;password=123456;pooling=true;charset=utf8"
  }
}

新建仓储

仓储里面有个可读的AppDbContext,用来直接调用,获取数据库信息
其中四种函数方法代表了不同的获取信息和增删改查
1、获取就直接用linq语句调用AppDbContext里面的Students属性就行
2、如果新增和删除,除了Add(),还需要保存,用到SaveChanges()方法
3、如果更新,除了用到SaveChanges()方法,还需要把状态student.State设为 Microsoft.EntityFrameworkCore.EntityState.Modified

public class SQLStudentRepository : IStudentRepository
    {
        private readonly AppDbContext dbContext;
        public SQLStudentRepository(AppDbContext dbContext)
        {
            this.dbContext = dbContext;
        }
        public Student GetStudent(int id)
        {
            var student = dbContext.Students.Find(id);
            return student;
        }

        public IEnumerable<Student> GetStudents()
        {
            var students = dbContext.Students;
            return students;
        }
        public Student AddStudent(Student student)
        {
            dbContext.Add(student);

            dbContext.SaveChanges();

            return student;
        }

        public Student UpdateStudent(Student updateStudent)
        {
            var student = dbContext.Students.Attach(updateStudent);

            student.State = Microsoft.EntityFrameworkCore.EntityState.Modified;

            dbContext.SaveChanges();

            return updateStudent;
        }

        public Student DeleteStudent(int id)
        {
            Student student = dbContext.Students.Find(id);

            if(student != null)
            {
                dbContext.Students.Remove(student);

                dbContext.SaveChanges();
            }

            return student;
        }
    }

在启动类中添加DbContext的连接配置和依赖注入

public class Startup
    {
        private readonly IConfiguration _configuration;
        public Startup(IConfiguration configuration)
        {
            _configuration = configuration;
        }
        public void ConfigureServices(IServiceCollection services)
        {
            string SQLString = _configuration.GetConnectionString("MysqlConnectString");
            services.AddDbContextPool<AppDbContext>(
                option => option.UseMySql(SQLString));
                
            services.AddScoped<IStudentRepository, SQLStudentRepository>();
            ``````
        }
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            ``````
        }
    }

数据库迁移

目前有两种形式:
1、已经有数据库表,则不需要迁移这一步
2、如果没有数据库表,则需要迁移这一步

1、打开程序包管理器控制台
在这里插入图片描述
2、讲需要迁移的程序项目设为启动项目
3、程序包管理器控制台默认项目设为要迁移的项目
4、输入Add-Migration 名称,添加迁移的信息
在这里插入图片描述
项目里面就会添加下面文件夹,里面包含每次的迁移
在这里插入图片描述
5、输入Update-Database完成迁移
在这里插入图片描述
数据库会有一个两个表,一个是迁移的配置表,一个是迁移的表
在这里插入图片描述
以上为迁移最正常的流程,接下来介绍几个点
1、AppDbContextModelSnapshot文件,里面包含的是我们添加类到数据的一些属性配置信息

[DbContext(typeof(AppDbContext))]
    partial class AppDbContextModelSnapshot : ModelSnapshot
    {
        protected override void BuildModel(ModelBuilder modelBuilder)
        {
#pragma warning disable 612, 618
            modelBuilder
                .HasAnnotation("ProductVersion", "3.1.32")
                .HasAnnotation("Relational:MaxIdentifierLength", 64);

            modelBuilder.Entity("WebApplication3.Student", b =>
                {
                    b.Property<int>("Id")
                        .ValueGeneratedOnAdd()
                        .HasColumnType("int");

                    b.Property<int>("ClassName")
                        .HasColumnType("int");

                    b.Property<string>("Email")
                        .IsRequired()
                        .HasColumnType("longtext CHARACTER SET utf8mb4");

                    b.Property<string>("Name")
                        .IsRequired()
                        .HasColumnType("varchar(50) CHARACTER SET utf8mb4")
                        .HasMaxLength(50);

                    b.HasKey("Id");

                    b.ToTable("Students");
                });
#pragma warning restore 612, 618
        }
    }

2、20230330125520_mysql_first文件,里面包含我们up更新了什么内容,down删除了什么内容

public partial class mysql_first : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "Students",
                columns: table => new
                {
                    Id = table.Column<int>(nullable: false)
                        .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
                    Name = table.Column<string>(maxLength: 50, nullable: false),
                    Email = table.Column<string>(nullable: false),
                    ClassName = table.Column<int>(nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Students", x => x.Id);
                });
        }

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

3、如果只是Add-Migration还没有Update-Database完成迁移的时候,不想迁移了,就可以通过remove-migration来删除这一次的迁移添加
4、如果已经迁移,想退回某个点怎么办
比如如果想要从前文的20230410110657_mysql_second回滚到20230401060420_mysql_first_home,就需要输入Update-Database mysql_first_home,数据库就会更新归滚到mysql_first_home
旧数据配置表
在这里插入图片描述
新数据库表
在这里插入图片描述
Student表也进行的回退更新,但是文件夹里还在怎么办
在这里插入图片描述
直接输入remove-migration,即可删除之前的迁移

总结一下:
如果想要回滚到某个迁移,先用Update-Database 名称,回滚数据库,新增迁移都还能保留,如果想用某次迁移,再用一次Update-Database 名称。
如果后面的新增迁移都不想要了,再多次remove-migration,删除项目增加的迁移文件。

5、如果想在建表的时候添加原始数据怎么办
在AppDbContext添加代码,进行迁移即可

public class AppDbContext : DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
        {
            
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Student>().HasData(
                new Student
                {
                    Id = 1,
                    Name = "小虎",
                    ClassName = ClassNameEnum.SecondGrade,
                    Email = "ads@qq.com"
                });
        }
        public DbSet<Student> Students { get; set; }
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值