我们已经知道了在OnModelCreating()方法中可以通过FluentApi对所有的实体类进行配置,然而当实体类很多时,我们把所有的配置都放在OnModelCreating()方法中很难维护。EF6允许我们给每一个实体添加一个单独的配置类,通过这个配置类来对相应的实体进行配置。
以配置Student实体类为例,我们在OnModelCreating()方法中配置Student实体,代码如下:
public class SchoolDBContext: DbContext
{
public SchoolDBContext(): base()
{
} public DbSet<Student> Students { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Student>().ToTable("StudentInfo"); modelBuilder.Entity<Student>().HasKey<int>(s => s.StudentKey); modelBuilder.Entity<Student>()
.Property(p => p.DateOfBirth)
.HasColumnName("Birthday")
.HasColumnOrder()
.HasColumnType("datetime2"); modelBuilder.Entity<Student>()
.Property(p => p.StudentName)
.HasMaxLength(); modelBuilder.Entity<Student>()
.Property(p => p.StudentName)
.IsConcurrencyToken(); modelBuilder.Entity<Student>()
.HasMany<Course>(s => s.Courses)
.WithMany(c => c.Students)
.Map(cs =>
{
cs.MapLeftKey("StudentId");
cs.MapRightKey("CourseId");
cs.ToTable("StudentCourse");
});
}
}
我们可以将每个实体类的配置放在一个对应的的配置类,(如Studnet的实体配置在StudentEntityConfiguratinos配置类中),如果程序中有很多实体类,采用单独配置的方式可以很好的提高配置的可维护性和可读性。
步骤如下:
步骤①:创建一个StudentEntityConfiguratinos类,这个类继承 EntityTypeConfiguration<TEntity> ,代码如下:
public class StudentEntityConfiguration: EntityTypeConfiguration<Student>
{
public StudentEntityConfiguration()
{
this.ToTable("StudentInfo"); this.HasKey<int>(s => s.StudentKey); this.Property(p => p.DateOfBirth)
.HasColumnName("DoB")
.HasColumnOrder()
.HasColumnType("datetime2"); this.Property(p => p.StudentName)
.HasMaxLength(); this.Property(p => p.StudentName)
.IsConcurrencyToken(); this.HasMany<Course>(s => s.Courses)
.WithMany(c => c.Students)
.Map(cs =>
{
cs.MapLeftKey("StudentId");
cs.MapRightKey("CourseId");
cs.ToTable("StudentCourse");
});
}
}
步骤②: 在OnModelCreating()方法中使用上边的配置类:
public class SchoolDBContext: DbContext
{
public SchoolDBContext(): base()
{
} public DbSet<Student> Students { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// 添加Student实体的配置
modelBuilder.Configurations.Add(new StudentEntityConfiguration());
}
}