Recently I needed to change my model so that a field would be checked for uniqueness. I eagerly added the [StringLength(3)]
and [Index(IsUnique = true)]
annotations to the model and ran Add-Migration
and Update-Database
. Close, but no cigar unfortunately. Update-Database kept throwing the following error: System.Data.SqlClient.SqlException (0x80131904): Column 'IsoCode' in table 'dbo.CurrencyModels' is of a type that is invalid for use as a key column in an index.
This is due to the fact that the generated code migration, was only applying the index and not the length restriction. You can fix this directly in the Up()
and Down()
methods of the code migration by using AlterColumn()
as follows:
public partial class UniqueCurrency : DbMigration { public override void Up() { AlterColumn("dbo.CurrencyModels", "IsoCode", c => c.String(maxLength: 3)); CreateIndex("dbo.CurrencyModels", "IsoCode", unique: true); } public override void Down() { AlterColumn("dbo.CurrencyModels", "IsoCode", c => c.String(maxLength: null)); DropIndex("dbo.CurrencyModels", new[] { "IsoCode" }); } }