【译】第30节---将配置移动到独立类中
到目前为止,我们已经在前面的章节中配置了OnModelCreating方法中的所有域类。 当有大量的域类时,在OnModelCreating中配置每个类都可能变得无法管理。
Code-First能够将与一个域类相关的所有配置移动到单独的类。
在下面的例子中,我们配置了Student实体:
public class SchoolDBContext: DbContext { public SchoolDBContext(): base() { } public DbSet<Student> Students { get; set; } public DbSet<Standard> Standards { get; set; } public DbSet<StudentAddress> StudentAddress { 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("DoB") .HasColumnOrder(3) .HasColumnType("datetime2"); modelBuilder.Entity<Student>() .Property(p => p.StudentName) .HasMaxLength(50); 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"); }); } }
现在,可以将与Student实体相关的所有配置移动到从EntityTypeConfiguration <TEntity>派生的单独类。
看下面的StudentEntityConfigurations类:
public class StudentEntityConfiguration: EntityTypeConfiguration<Student> { public StudentEntityConfiguration() { this.ToTable("StudentInfo"); this.HasKey<int>(s => s.StudentKey); this.Property(p => p.DateOfBirth) .HasColumnName("DoB") .HasColumnOrder(3) .HasColumnType("datetime2"); this.Property(p => p.StudentName) .HasMaxLength(50); 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"); }); } }
如上面代码所示,我们已将Student实体的所有配置移动到StudentEntityConfiguration的构造函数中,该构造函数继承自EntityTypeConfiguration <Student>。
需要在包含配置的通用占位符中指定实体类型,此处为Student。
现在,可以通知有关此类的Fluent API,如下所示:
public class SchoolDBContext: DbContext { public SchoolDBContext(): base() { } public DbSet<Student> Students { get; set; } public DbSet<Standard> Standards { get; set; } public DbSet<StudentAddress> StudentAddress { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { // Moved all Student related configuration to StudentEntityConfiguration class modelBuilder.Configurations.Add(new StudentEntityConfiguration()); } }
因此,你可以使用单独的类来配置域类,以提高可读性和可维护性。