DropColumn conditionally in migration
I want to drop a column in my migration Up
. I am using EF 5.
DropColumn("dbo.MyObjects", "AttributeId");
The problem is that in some way some of the database instances do not have this column (as described above). I am thinking about dropping it with Sql
and searching in sys.columns
or wrap the DropColumn in try ... catch
.
But maybe there is some known way to do this with Entity Framework migrations?
+2
source to share
1 answer
My column also had a default constraint, so I ended up with this:
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 it saves time.
+1
source to share