.NetFramwork下EntityFramework Codefirst用例
作者:互联网
``#### Codefirst
-
创建Model文件夹
-
Model文件夹下创建两个类(你随意,想怎么写就怎么写)
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; }
}
- 创建一个上下文类
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; }
}
-
既然是EF的ORM框架,使用Nuget下载EF(注意引用下是否有两个关于EntityFramework的应用,类似Java的jdbc)
-
配置链接 到数据库
在App.config配置文件下找到,在它同级标签下配置数据库链接字符串
未配置
配置完
- 现在只需要进行迁移
首先生成一下
然后在程序包管理器控制台
执行就可以了
-
enable-migrations//启动迁移
自动生成
-
add-migration 'createSchool'
-
update-database
大功告成!
参考:
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
标签:Codefirst,set,string,get,Grade,EntityFramework,用例,modelBuilder,public 来源: https://www.cnblogs.com/galatia/p/14747849.html