223

Basically I got a table in my EF database with the following properties:

public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Image { get; set; }
public string WatchUrl { get; set; }
public int Year { get; set; }
public string Source { get; set; }
public int Duration { get; set; }
public int Rating { get; set; }
public virtual ICollection<Category> Categories { get; set; }

It works fine however when I change the int of Rating to be a double I get the following error when updating the database:

The object 'DF_Movies_Rating__48CFD27E' is dependent on column 'Rating'. ALTER TABLE ALTER COLUMN Rating failed because one or more objects access this column.

What's the issue?

Joe Taras
  • 15,166
  • 7
  • 42
  • 55
Jordan Axe
  • 3,823
  • 6
  • 20
  • 27
  • 1
    Remove the constraint DF_Movies_Rating__48CFD27E and then change the type of your field – Joe Taras Oct 19 '13 at 00:45
  • @JoeTaras But I have never created a constraint named that. What is it and where do I find it? – Jordan Axe Oct 19 '13 at 00:49
  • 2
    When you create a field DBMS create automatically a constraint. If you expand your table info, in constraint section you'll find it. Tell me if you'll find ;) – Joe Taras Oct 19 '13 at 01:05

8 Answers8

330

Try this:

Remove the constraint DF_Movies_Rating__48CFD27E before changing your field type.

The constraint is typically created automatically by the DBMS (SQL Server).

To see the constraint associated with the table, expand the table attributes in Object explorer, followed by the category Constraints as shown below:

Tree of your table

You must remove the constraint before changing the field type.

Sᴀᴍ Onᴇᴌᴀ
  • 8,218
  • 8
  • 36
  • 58
Joe Taras
  • 15,166
  • 7
  • 42
  • 55
  • How to delete that constraints? – ManirajSS Oct 23 '14 at 12:04
  • 69
    @ManirajSS: ALTER TABLE yourtable DROP CONSTRAINT DF_Movies_Rating__48CFD27E – Joe Taras Oct 23 '14 at 12:32
  • 27
    What triggered the creation of the constraint? I have a bunch of them, and I really don't want them! – Simon Parker Apr 15 '15 at 04:10
  • 5
    Hmm, and what to do if I want to use DB migrations of my framework (Laravel) and dropColumn there? I have no idea how to drop the constraint which has mysterious name, autogenerated by SQL server :( – JustAMartin Feb 15 '16 at 16:00
  • Which version of Sql Server have you got? – Joe Taras Feb 16 '16 at 07:26
  • So why this constrains appear from nothing? And deleting with hardcoding their names is annoying. Is there any solution of this - drop column withoud hardcoding this ugly constrains? – DPM Mar 20 '16 at 13:56
  • Why does it recreate itself after deleting it?!! – mshwf Oct 26 '16 at 16:26
  • @MohamedAhmed: Are you sure? The solution to drop column is remove it, so it's no possible – Joe Taras Oct 26 '16 at 17:21
  • 2
    I'm sure: I droped it and the folder Constraints becomes empty, and when I run the application or call the `update-database` it recreate itself again I posted this issue : http://stackoverflow.com/questions/40267769/dependencies-error-after-changing-data-type-in-entity-framework – mshwf Oct 26 '16 at 17:25
  • 7
    Why the heck doesn't SQLServer drop the contraint implicitly? It did, after all, create it implicitly! – youcantryreachingme Oct 03 '18 at 00:03
  • @youcantryreachingme: Because the creation can be a facility about performance, but when you want to drop something, you are in production mode, so any change can be dangerous – Joe Taras Oct 03 '18 at 06:36
  • 1
    Very late answer but may help anybody else coming into this. I can't tell what SQL properties are used to create the Ratings property, but my best guess is that it is not nullable, that would create an implicit constraint. – Reg Smith Nov 21 '18 at 14:32
72

I'm adding this as a response to explain where the constraint comes from. I tried to do it in the comments but it's hard to edit nicely there :-/

If you create (or alter) a table with a column that has default values it will create the constraint for you.

In your table for example it might be:

CREATE TABLE Movie (
    ...
    rating INT NOT NULL default 100
)

It will create the constraint for default 100.

If you instead create it like so

CREATE TABLE Movie (
  name VARCHAR(255) NOT NULL,
  rating INT NOT NULL CONSTRAINT rating_default DEFAULT 100
);

Then you get a nicely named constraint that's easier to reference when you are altering said table.

ALTER TABLE Movie DROP CONSTRAINT rating_default;
ALTER TABLE Movie ALTER COLUMN rating DECIMAL(2) NOT NULL;
-- sets up a new default constraint with easy to remember name
ALTER TABLE Movie ADD CONSTRAINT rating_default DEFAULT ((1.0)) FOR rating;

You can combine those last 2 statements so you alter the column and name the constraint in one line (you have to if it's an existing table anyways)

h3adache
  • 1,296
  • 11
  • 18
  • Thanks for adding info on how to avoid the issue by naming all constraints in the first place. (That is, avoid the issue of dropping randomly named constraints) – youcantryreachingme Oct 03 '18 at 00:06
50

This is the tsql way

 ALTER TABLE yourtable DROP CONSTRAINT constraint_name     -- DF_Movies_Rating__48CFD27E

For completeness, this just shows @Joe Taras's comment as an answer

Saic Siquot
  • 6,513
  • 5
  • 34
  • 56
33

As constraint has unpredictable name, you can write special script(DropConstraint) to remove it without knowing it's name (was tested at EF 6.1.3):

public override void Up()
{    
    DropConstraint();
    AlterColumn("dbo.MyTable", "Rating", c => c.Double(nullable: false));
}

private void DropConstraint()
{
    Sql(@"DECLARE @var0 nvarchar(128)
          SELECT @var0 = name
          FROM sys.default_constraints
          WHERE parent_object_id = object_id(N'dbo.MyTable')
          AND col_name(parent_object_id, parent_column_id) = 'Rating';
          IF @var0 IS NOT NULL
              EXECUTE('ALTER TABLE [dbo].[MyTable] DROP CONSTRAINT [' + @var0 + ']')");
}

public override void Down()
{            
    AlterColumn("dbo.MyTable", "Rating", c => c.Int(nullable: false));    
}
Slava Utesinov
  • 13,410
  • 2
  • 19
  • 26
  • This answer works great in a Migration-based environment where you can't afford to hardcode constraint name. – Menion Leah Nov 04 '16 at 16:59
  • If you make a wrapper/extension/overloaded function for AlterColumn - like AlterColumnX - you can include that DropConstraint logic in there - and you can pass in the table name & column name so you don't have to write them again. – N73k Oct 19 '17 at 01:09
14

When we try to drop a column which is depended upon then we see this kind of error:

The object 'DF__*' is dependent on column ''.

drop the constraint which is dependent on that column with:

ALTER TABLE TableName DROP CONSTRAINT dependent_constraint;

Example:

Msg 5074, Level 16, State 1, Line 1

The object 'DF__Employees__Colf__1273C1CD' is dependent on column 'Colf'.

Msg 4922, Level 16, State 9, Line 1

ALTER TABLE DROP COLUMN Colf failed because one or more objects access this column.

Drop Constraint(DF__Employees__Colf__1273C1CD):

ALTER TABLE Employees DROP CONSTRAINT DF__Employees__Colf__1273C1CD;

Then you can Drop Column:

Alter Table TableName Drop column ColumnName
Sᴀᴍ Onᴇᴌᴀ
  • 8,218
  • 8
  • 36
  • 58
Jinna Balu
  • 6,747
  • 38
  • 47
3

Solution :

open database table -> expand table -> expand constraints and see this

screenshot

Community
  • 1
  • 1
  • While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – Donald Duck Jan 16 '17 at 13:02
1

While dropping the columns from multiple tables, I faced following default constraints error. Similar issue appears if you need to change the datatype of column.

The object 'DF_TableName_ColumnName' is dependent on column 'ColumnName'.

To resolve this, I have to drop all those constraints first, by using following query

DECLARE @sql NVARCHAR(max)=''     
SELECT @SQL += 'Alter table ' + Quotename(tbl.name) + '  DROP constraint ' + Quotename(cons.name) + ';'
 FROM SYS.DEFAULT_CONSTRAINTS cons 
 JOIN   SYS.COLUMNS col ON col.default_object_id = cons.object_id
 JOIN   SYS.TABLES tbl ON tbl.object_id = col.object_id
 WHERE  col.[name] IN ('Column1','Column2')

--PRINT @sql
EXEC Sp_executesql @sql 

After that, I dropped all those columns (my requirement, not mentioned in this question)

DECLARE @sql NVARCHAR(max)='' 
SELECT @SQL += 'Alter table ' + Quotename(table_catalog)+ '.' + Quotename(table_schema) + '.'+ Quotename(TABLE_NAME) 
               + '  DROP column ' + Quotename(column_name) + ';'
FROM   information_schema.columns where COLUMN_NAME IN ('Column1','Column2')  
--PRINT @sql
EXEC Sp_executesql @sql 

I posted here in case someone find the same issue.

Happy Coding!

Sheikh M. Haris
  • 892
  • 1
  • 9
  • 17
  • Where does this code drop constraints? It drops columns, and rather dangerously. Also, please notice that [this answer](https://stackoverflow.com/a/40001468/861716) already shows a way too generate the required SQL. – Gert Arnold Nov 23 '20 at 15:50
  • @GertArnold The answer you have mentioned is for a specific table, whereas my script is for multiple table having similar column name. Also, I have modified the answer and added the constraints part. Thanks for mentioning. – Sheikh M. Haris Dec 06 '20 at 06:51
-1

I had this error trying to run a migration to work around it I renamed the column and re-generated the migration using

add-migration migrationname -force

in the package manager console. I was then able to run

update-database

successfully.

Kirsten
  • 15,730
  • 41
  • 179
  • 318
  • 2
    Be careful, this doesn't rename a column - it drops the column and adds a new column. You will lose any data that used to exist in the column unless you add custom code in the migration. – caesay Jan 18 '18 at 19:51