MigrationsBuilder Class
Represents a tool for building a Migration. This class is used by the EF Core tooling to generate the code for migrations.
namespace Microsoft.EntityFrameworkCore.Migrations
public class MigrationsBuilder
Description
The MigrationsBuilder class provides a fluent API for defining the operations that should be performed by a migration. These operations typically involve schema changes to your database, such as creating tables, adding columns, or modifying constraints.
Methods
AddColumn<TProperty>(string table, string name, Action<ColumnOperation> property = null)
public virtual ColumnOperation AddColumn<TProperty>(string table, string name, Action<ColumnOperation> property = null)
Adds a new column to an existing table.
Parameters
- string table
- The name of the table to add the column to.
- string name
- The name of the new column.
- Action<ColumnOperation> property
- An optional action to configure the properties of the column.
Returns
ColumnOperation: An object representing the operation to add the column.
CreateTable(string name, Action<TableOperation> columns)
public virtual TableOperation CreateTable(string name, Action<TableOperation> columns)
Creates a new table in the database.
Parameters
- string name
- The name of the table to create.
- Action<TableOperation> columns
- An action to define the columns and constraints of the table.
Returns
TableOperation: An object representing the operation to create the table.
DropTable(string name)
public virtual TableOperation DropTable(string name)
Drops an existing table from the database.
Parameters
- string name
- The name of the table to drop.
Returns
TableOperation: An object representing the operation to drop the table.
Example
Using MigrationsBuilder to create a migration
using Microsoft.EntityFrameworkCore.Migrations;
namespace MyProject.Migrations
{
public partial class AddUsersTable : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Users",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
Username = table.Column<string>(maxLength: 50),
Email = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Users", x => x.Id);
});
migrationBuilder.AddColumn<DateTime>(
name: "CreatedAt",
table: "Users",
nullable: false,
defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc));
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "CreatedAt",
table: "Users");
migrationBuilder.DropTable(
name: "Users");
}
}
}