DropColumn conditionally in a migration

ⅰ亾dé卋堺 提交于 2019-12-24 03:12:48

问题


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:


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.



来源:https://stackoverflow.com/questions/20904865/dropcolumn-conditionally-in-a-migration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!