.net core中EF core的环境搭建

//数据上下文MyDbContext.cs
using
Microsoft.EntityFrameworkCore; namespace Learn00.Models { public class MyDbContext: DbContext { //摘要: // 把Employees { get; set; },理解成是一个容器 // 用来存放Employee类型的实体,该实体名字叫做Employees // 该容器的作用是用来实现实体类到数据库表的映射 // 映射的时机: Program.cs 里调用 await ctx.SaveChangesAsync(); public DbSet<Student> Employees { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { //摘要: 下面的连接字符串是用来连接sqlservr用的: //连接SQLserver需要nuget安装 Microsoft.EntityFrameworkCore.SqlServer //以下是代码: //string connStr = "Server=.;Database=demo1;Trusted_Connection=True;Encrypt=false;"; //optionsBuilder.UseSqlServer(connStr); //摘要:下面的连接字符串是用来连接mysql用的 // 同时还需要指定mysql的版本号 // 连接MySQL需要nuget安装 Pomelo.EntityFrameworkCore.MySql // string MySqlConneStr = "server=localhost;user=root;password=sy123456;database=learn00"; //特别注意:此处使用的是:Pomelo.EntityFramework.MySql包. var serverVersion = new MySqlServerVersion(new Version(8, 0, 34)); optionsBuilder.UseMySql(MySqlConneStr, serverVersion); } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly); } } }
//Student.cs 数据库实体类(实体映射类)
using
System.ComponentModel.DataAnnotations.Schema; namespace Learn00.Models { [Table("StudentInfo")] public class Student { public int ID { get; set; } public string LastName { get; set; } public string FirstMidName { get; set; } public DateTime EnrollmentDate { get; set; } } }


//数据库迁移命令 程序包管理控制台

 

Add-Migration InitialCreate    //InitialCreate是生成迁移文件的文件名,执行此命令后,会生成Migrations文件夹及相关的迁移文件
Update-Database //生成数据库

 

 

visual studio 后面有阴影代码提示,tab直接打印选中

 

vs 2022 多行注释  ctrl k + ctrl c

posted @ 2024-04-07 15:04  爱晒太阳的懒猫。。  阅读(10)  评论(0编辑  收藏  举报