In Entity Framework code-first, if you have a domain model like the following:

public class Country
{
    public int Id { get; set; }

    [Index]
    public string IsoCode { get; set; }
}

and want to create an index for a string property, when you execute `update-database` for your migration, you may end up with the following error:

[box type=”error” width=”100%” ]Column ‘{column_name}’ in table ‘{table_name}’ is of a type that is invalid to use as key column in an index.[/box]

This usually happens when you use `VARCHAR(max)`, which is the default column type when creating a string property in EF.

To make it work properly you need to specify the maximum length of your string property, so that the above model may be transformed to:

public class Country
{
    public int Id { get; set; }

    [Index]
    [Column(TypeName = "VARCHAR")]
    [StringLength(2)]
    public string IsoCode { get; set; }
}

Then, when you update your database using `update-database` command the execution will be completed successfully.

 

Categorized in:

Tagged in:

, ,