EF CodeFirst系列(7)--- FluentApi配置单个实体
我们已经知道了在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(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"); }); } }
我们可以将每个实体类的配置放在一个对应的的配置类,(如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(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"); }); } }
步骤②: 在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()); } }
分类:
03 Linq/EF
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决