I want to create a table in the "Secondary" file group which has been created previously in the SQL Server 2016. I want to create this table with EF core code-first.
Finally, I found the solution and I want to share it.
PM> add-migration CreateSecondaryFileGroup
protected override void Up(MigrationBuilder migrationBuilder)
{
//create FILEGROUP
migrationBuilder.Sql(
" EXEC('ALTER DATABASE [YourDatabaseName] ADD FILEGROUP [Secondary]')",
suppressTransaction: true);
//Create Physical file
migrationBuilder.Sql(
"ALTER DATABASE [YourDatabaseName] " +
"ADD FILE " +
"( " +
"NAME = 'Secondary_Data', " +
"FILENAME = '[yourFileDirectory]' " +
//for example:
//"FILENAME = 'D:\\Program Files\\Microsoft SQL Server\\MSSQL13.MSSQLSERVER\\MSSQL\\DATA\\Abby_Data2.mdf' " +
") " +
"TO FILEGROUP Secondary",
suppressTransaction:true
);
}
PM> update-database
public DbSet<Category> Category { get; set; }
PM> add-migration CreateCategoryTableInSecondaryFileGroup
One solution to create or move a table to another filegroup is to create Clustered Index in the specific filegroup. The clustered index is the primary key of the “Category” table whose name is “PK_Category”
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Category",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: false),
DisplayOrder = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Category", x => x.Id);
});
///// this below code is the key point
///// you should write the below code
migrationBuilder.Sql(
"CREATE UNIQUE CLUSTERED INDEX PK_Category ON Category (Id)"+
" WITH(DROP_EXISTING = ON) "+
" ON Secondary"
, suppressTransaction:true);
}
PM> update-database