如何使用EF Core code-first在SQL Server指定文件组中创建数据表
实现步骤
1. 自定义表配置扩展方法
EF Core原生没有直接指定SQL Server文件组的配置接口,我们先扩展Fluent API用来标记目标文件组:
public static class RelationalModelBuilderExtensions { public static readonly string FileGroupAnnotationName = "SqlServer:FileGroup"; // 带schema的重载 public static EntityTypeBuilder<TEntity> ToTable<TEntity>(this EntityTypeBuilder<TEntity> builder, string tableName, string schema, string fileGroup) where TEntity : class { builder.ToTable(tableName, schema); builder.HasAnnotation(FileGroupAnnotationName, fileGroup); return builder; } // 不带schema的重载 public static EntityTypeBuilder<TEntity> ToTable<TEntity>(this EntityTypeBuilder<TEntity> builder, string tableName, string fileGroup) where TEntity : class { builder.ToTable(tableName); builder.HasAnnotation(FileGroupAnnotationName, fileGroup); return builder; } }
2. 为目标实体指定Secondary文件组
在你的DbContext的OnModelCreating方法中,给需要放到Secondary文件组的表加配置:
protected override void OnModelCreating(ModelBuilder modelBuilder) { // 示例:将Product实体对应的Products表放到Secondary文件组 modelBuilder.Entity<Product>() .ToTable("Products", "Secondary"); // 其他需要指定文件组的实体按同理配置即可 }
3. 自定义迁移SQL生成器
重写EF Core默认的SQL Server迁移生成逻辑,识别我们加的文件组注解,在生成建表语句时追加文件组配置:
public class FileGroupAwareSqlServerMigrationsSqlGenerator : SqlServerMigrationsSqlGenerator { public FileGroupAwareSqlServerMigrationsSqlGenerator( MigrationsSqlGeneratorDependencies dependencies, IRelationalAnnotationProvider migrationsAnnotations) : base(dependencies, migrationsAnnotations) { } protected override void Generate(CreateTableOperation operation, IModel model, MigrationCommandListBuilder builder) { // 先生成默认的建表语句 base.Generate(operation, model, builder); // 读取文件组注解 var fileGroup = operation.FindAnnotation(RelationalModelBuilderExtensions.FileGroupAnnotationName)?.Value as string; if (!string.IsNullOrWhiteSpace(fileGroup)) { // 移除默认语句末尾的分号,追加文件组配置后再补分号 builder.Length--; builder.Append($" ON [{fileGroup}]"); builder.AppendLine(Dependencies.SqlGenerationHelper.StatementTerminator); builder.EndCommand(); } } }
4. 替换默认的迁移生成器服务
在服务注册时替换EF Core默认的迁移SQL生成器为我们自定义的实现:
// .NET 6+ 顶级语句写法 builder.Services.AddDbContext<你的DbContext类名>(options => options.UseSqlServer("你的数据库连接字符串") .ReplaceService<IMigrationsSqlGenerator, FileGroupAwareSqlServerMigrationsSqlGenerator>()); // 旧版Startup.cs写法 services.AddDbContext<你的DbContext类名>(options => options.UseSqlServer(Configuration.GetConnectionString("你的连接字符串配置名")) .ReplaceService<IMigrationsSqlGenerator, FileGroupAwareSqlServerMigrationsSqlGenerator>());
5. 执行迁移生成表
正常执行EF Core迁移命令即可:
- 包管理器控制台执行:
Add-Migration 迁移名称 - 再执行:
Update-Database
生成的表会自动创建在你预先建好的Secondary文件组下。
注意:如果是已存在的表需要迁移到Secondary文件组,可在迁移的Up方法中手动执行SQL语句:
Sql("ALTER TABLE [表名] REBUILD PARTITION = ALL ON [Secondary]")即可。
内容的提问来源于stack exchange,提问作者Mahdi Abyaznezhad
相关产品推荐
相关产品推荐

