EF CodeFirst的步骤
1 创建各个实体类
2 创建一个空数据模型,然后删除掉,为了引入Entity Framework和System.Data.Entity
3 为实体类增加标注
4 为实体增加导航属性
5 在App.config configuration标签里面增加connectionStrings标签,并增加连接字符串
6 创建数据操作类继承DbContext ,构造函数参数为“name=connStr”
7 增加两个DbSet属性,对应操作的实体
8 重写OnModelCreating方法,使得生成的表不包含复数;
9 调用context.Database.CreateIfNotExists()在对应的数据库下面生成表
10 通过数据操作类操作表
//ClassInfo
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeFirstDemo
{
public class ClassInfo
{
[Key]
public int Id { get; set; }
[Required]
[StringLength(32)]
public string ClassName { get; set; }
[Required]
public DateTime CreateTime { get; set; }
public ICollection<StudentInfo> StudentInfo { get; set; }
}
}
//StudentInfo
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeFirstDemo
{
public class StudentInfo
{
[Key]
public int Id { get; set; }
[Required]
[StringLength(32)]
public string StudentName { get; set; }
[Required]
public DateTime CreateTime { get; set; }
[Required]
public ClassInfo ClassInfo { get; set; }
}
}
//MyDataContext
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeFirstDemo
{
public class MyDataContext:DbContext
{
public MyDataContext()
: base("name = ConnStr")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
public DbSet<ClassInfo> ClassInfo { get; set; }
public DbSet<StudentInfo> StudentInfo { get; set; }
}
}
//主方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeFirstDemo
{
class Program
{
static void Main(string[] args)
{
MyDataContext db = new MyDataContext();
db.Database.CreateIfNotExists();
ClassInfo classInfo = new ClassInfo();
classInfo.ClassName = "abc";
classInfo.CreateTime = DateTime.Now;
db.ClassInfo.Add(classInfo);
StudentInfo stu1 = new StudentInfo();
stu1.StudentName = "zhangsan";
stu1.CreateTime = DateTime.Now;
stu1.ClassInfo = classInfo;
StudentInfo stu2 = new StudentInfo();
stu2.StudentName = "Lisi";
stu2.CreateTime = DateTime.Now;
stu2.ClassInfo = classInfo;
db.StudentInfo.Add(stu1);
db.StudentInfo.Add(stu2);
db.SaveChanges();
}
}
}