Search code examples
c#entity-framework-coreef-code-first

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");

Solution

  • 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.