Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create table in migration code first if it does not exist

I have two projects which are code-first, they use the same database, so I want to check whether a table exists in migration. If it does not yet exist, the project should create it, and if it exists, just ignore it.

This is the code which is generated in the migration class, when I enter "Add-migration init". How can I execute it only if the Categories table does not exist yet?

   migrationBuilder.CreateTable(
            name: "Categories",
            columns: table => new
            {
                Id = table.Column<long>(type: "bigint", nullable: false)
                    .Annotation("SqlServer:Identity", "1, 1"),
                Name = table.Column<string>(type: "nvarchar(max)", nullable: false),
                ParentCategoryId = table.Column<long>(type: "bigint", nullable: true)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_Categories", x => x.Id);
                table.ForeignKey(
                    name: "FK_Categories_Categories_ParentCategoryId",
                    column: x => x.ParentCategoryId,
                    principalTable: "Categories",
                    principalColumn: "Id");
            });

        migrationBuilder.CreateIndex(
            name: "IX_Categories_ParentCategoryId",
            table: "Categories",
            column: "ParentCategoryId");
like image 765
nnmmss Avatar asked Oct 23 '25 00:10

nnmmss


1 Answers

You would have to write the entire CREATE TABLE IF NOT EXISTS statement using migrationBuilder.Sql().

A better way manage this situation is to let one of the contexts have full ownership of the table and use ExcludeFromMigrations in the other context. Of course, this means that you'll have to apply migrations for both contexts before the one it's excluded from will work.

like image 104
bricelam Avatar answered Oct 24 '25 12:10

bricelam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!