.NetFramwork下EntityFramework Codefirst用例

``#### Codefirst

  1. 创建Model文件夹
    .NetFramwork下EntityFramework Codefirst用例

  2. Model文件夹下创建两个类(你随意,想怎么写就怎么写)
    .NetFramwork下EntityFramework Codefirst用例

public class Grade
    {
        [Required]
        public int GradeId { get; set; }
        public string GradeName { get; set; }
        public string Section { get; set; }
        public List<Student> Students { get; set; }
    }
public class Student
    {
        [Required]
        public int StudentID { get; set; }
        [StringLength(maximumLength:50),Column(TypeName ="nvarchar")]
        public string StudentName { get; set; }
        public DateTime? DateOfBirth { get; set; }
        public byte[] Photo { get; set; }
        public decimal Height { get; set; }

        [ForeignKey(nameof(Grade))]
        public int GradeID { get; set; }
        public Grade Grade { get; set; }
    }
  1. 创建一个上下文类
public class SchoolContext : DbContext
    {
        //构造函数
        public SchoolContext() : base(nameOrConnectionString: "SchoolContext")//绑定app.config文件的链接字符串
        {
            Database.SetInitializer<SchoolContext>(strategy: null);//CodeFirst 上下文的默认策略是 System.Data.Entity.CreateDatabaseIfNotExists 的实例。
        }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
            modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
        }
        public DbSet<Student> Students { get; set; }
        public DbSet<Grade> Grades { get; set; }
    }
  1. 既然是EF的ORM框架,使用Nuget下载EF(注意引用下是否有两个关于EntityFramework的应用,类似Java的jdbc)
    .NetFramwork下EntityFramework Codefirst用例

  2. 配置链接 到数据库
    在App.config配置文件下找到,在它同级标签下配置数据库链接字符串

未配置

.NetFramwork下EntityFramework Codefirst用例

配置完

.NetFramwork下EntityFramework Codefirst用例

  1. 现在只需要进行迁移
    首先生成一下
    .NetFramwork下EntityFramework Codefirst用例
    然后在程序包管理器控制台执行就可以了
  • enable-migrations//启动迁移
    .NetFramwork下EntityFramework Codefirst用例
    自动生成
    .NetFramwork下EntityFramework Codefirst用例

  • add-migration 'createSchool'
    .NetFramwork下EntityFramework Codefirst用例
    .NetFramwork下EntityFramework Codefirst用例

  • update-database
    .NetFramwork下EntityFramework Codefirst用例

大功告成!

参考:
https://www.cnblogs.com/wyy1234/p/9660808.html
https://www.bilibili.com/video/BV1Z4411A7Qc?t=788

EF core参考
https://www.cnblogs.com/Vincent-yuan/p/10777664.html

上一篇:2021-06-20 .NET高级班 63-ASP.NET Core EFCore数据库(CodeFirst的使用)


下一篇:EF Core CodeFirst数据库自动迁移