I’m using EF 4.3.1 Code First Migrations. I have a table like:
public class Product
{
[Key]
[Column(Order=0)]
[MaxLength(100)]
public string Store { get; set; }
[Key]
[Column(Order=1)]
[MaxLength(100)]
public string Sku { get; set; }
}
I have an existing table created with the above code. I then moved it to a single-column Primary Key:
public class Product
{
[MaxLength(100)]
public string Store { get; set; }
[Key]
[MaxLength(100)]
public string Sku { get; set; }
}
This causes EF to fail in the next automatic migration, complaining:
ALTER TABLE [Product] ALTER COLUMN [Store] nvarchar
The object ‘PK_Product’ is dependent on column ‘Store’. ALTER
TABLE ALTER COLUMN Store failed because one or more objects access this
column.
Clearly the PK_Product needs to be dropped before attempting to fire this ALTER statement (why is it altering the column at all?), but instead the migration fails.
Am I doing something wrong or is this a bug? Workarounds?
You won’t be able to do this with an automatic migration. You’ll have to create a migration using
Add-Migrationand then change it so it only modifies the PK.The migration can be as simple as:
EF is altering the column because, when it’s part of a
Key, it’s implicitlyNOT NULL.You can leave it as-is, add a
[Required]attribute, or allow EF to alter the column after dropping the PK.