EF中的模型类的配置有DataAnnotations、FluentAPI 两种。
上面这种在模型类上[Table(“Persons”)]、[Column(“Password”)]这种方式就叫DataAnnotations这种方式比较方便,但是耦合度太高,一般的类最好是POCO(Plain Old C# Object,没有继承什么特殊的父类,没有标注什么特殊的Attribute,没有定义什么特殊的方法,就是一堆普通的属性);不符合大项目开发的要求。
微软推荐使用FluentAPI 的使用方式,因此后面主要用FluentAPI 的使用方式。
FluentAPI 配置
FluentAPI 配置Persons 的方式
假如数据库中有表Students,有Id(主键,自动增长)、Pwd、Name、CreateTime字段。
- 创建一个普通的实体类Student包含属性(Id,Pwd,Name,CreateTime)
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Pwd { get; set; }
public DateTime CreateTime { get; set; }
}
2.创建一个 PersonConfig 类,放到ModelConfig文件夹下(PersonConfig、EntityConfig这样的名字都不是必须的)
public class StudentConfig:EntityTypeConfiguration<Model.Student>
{
public StudentConfig()
{
this.ToTable("Students");
}
}
- 这个类可以立即为配置类,配置实体对象和数据库中表进行映射的一些规则。
注意:
(1)实体对象配置类必须继承EntityTypeConfiguration< T>泛型类
(2) 配置的实体对象是谁泛型类中T就是这个实体对象,一切和配置类的名字无任何关系
(3) this.ToTable()方法其实就是指这个实体对象在数据库中所映射的表的名字 - 创建数据库上下文类(InLettDbContext)
public class InLettDbContext:DbContext
{
public InLettDbContext() : base("name=con")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Configurations.AddFromAssembly(Assembly.GetExecutingAssembly());
}
public DbSet<Student>Students { get; set; }
}
modelBuilder.Configurations.AddFromAssembly(Assembly.GetExecutingAssembly());这行代码代表从这句话所在的程序集加载所有的继承自EntityTypeConfiguration为模型配置类。还有很多加载配置文件的做法(把配置写到OnModelCreating中或者把加载的代码写死到OnModelCreating中),但是这种做法是最符合大项目规范的做法。
和以前唯一的不同就是:模型不需要标注Attribute;编写一个XXXConfig类配置映射关系;DbContext 中override OnModelCreating;
4.测试
private void button1_Click(object sender, EventArgs e)
{
using (InLettDbContext context = new InLettDbContext())
{
Model.Student stu = new Model.Student()
{
Name = "张三",
Pwd = "123",
CreateTime = DateTime.Now
};
context.Students.Add(stu);
context.SaveChanges();
}
}