DropColumn conditionally in a migration

2019-07-23 21:07发布

I want to perform a column dropping in my Up migration. I am using EF 5.

DropColumn("dbo.MyObjects", "AttributeId");

The issue is that in some way part of database instances do not have that column (long story how). I am thinking of dropping it with Sql and searching in sys.columns, or wrapping DropColumn in try ... catch.

But maybe there is some known way to do it with Entity Framework migrations?

1条回答
Animai°情兽
2楼-- · 2019-07-23 21:39

There was also a default constraint on my column, so ended up with the following:

public override void Up()
{
    Sql(@"IF EXISTS(
     SELECT 1 FROM sys.columns c
     INNER JOIN sys.tables t ON t.object_id = c.object_id
     WHERE c.name = 'AttributeId' AND t.name = 'MyObjects')
     BEGIN
       DECLARE @AttributeIdDefConstraint nvarchar(128)
       SELECT @AttributeIdDefConstraint = name
       FROM sys.default_constraints
       WHERE parent_object_id = object_id(N'dbo.MyObjects')
         AND col_name(parent_object_id, parent_column_id) = 'AttributeId';
       IF @AttributeIdDefConstraint IS NOT NULL
       BEGIN
     EXECUTE('ALTER TABLE [dbo].[MyObjects] DROP CONSTRAINT ' + @AttributeIdDefConstraint)
       END
       ALTER TABLE [dbo].[MyObjects] DROP COLUMN [AttributeId]
     END");
}

Hope that will save one's time.

查看更多
登录 后发表回答