EF Code-First - Chuyển cấu hình Fluent API

Chuyển cấu hình Fluent API sang một lớp riêng trong Code First

Như bạn đã thấy trong các hướng dẫn trước, chúng tôi đã cấu hình tất cả các lớp thực thể bằng Fluent API trong phương thức OnModelCreating().

Tuy nhiên, nó trở nên khó duy trì nếu bạn cấu hình một số lượng lớn các lớp thực thể trong OnModelCreating.

EF 6 cho phép bạn tạo một lớp riêng cho từng thực thể và đặt tất cả các cấu hình liên quan đến thực thể trong lớp đó.

Hãy xem ví dụ sau nơi chúng ta cấu hình thực thể 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("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");
            });
    }
}

Bây giờ, bạn có thể di chuyển tất cả các cấu hình liên quan đến thực thể Student sang một lớp riêng có nguồn gốc từ EntityTypeConfiguration<TEntity>.

Hãy xem lớp StudentEntityConfigurations sau bao gồm tất cả các cấu hình cho thực thể Student.

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");
                });
    }
}

Như bạn có thể thấy ở trên, chúng tôi đã chuyển tất cả các cấu hình cho thực thể Student vào phương thức khởi tạo của lớp StudentEntityConfiguration, có nguồn gốc từ EntityTypeConfiguration<Student>.

Bây giờ, bạn cần thêm lớp cấu hình tùy chỉnh này sử dụng Fluent API, như ví dụ bên dưới.

public class SchoolDBContext: DbContext 
{
    public SchoolDBContext(): base() 
    {
    }

    public DbSet<Student> Students { get; set; }
        
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // Moved all Student related configuration to StudentEntityConfiguration class
        modelBuilder.Configurations.Add(new StudentEntityConfiguration());
    }
}

Do đó, bạn có thể sử dụng nhiều lớp cấu hình để tăng khả năng đọc và bảo trì.