41

I'm using Entity Framework 6.1 code-first and my domain model is below.

class Item
{
    [Index]
    public string CreatedBy { set; get; }
} 

When I use update-database for migration, I get the following error. However as far as I researched [Index] should work as annotation to string.

Column 'CreatedBy' in table 'dbo.Items' is of a type that is invalid for use as a key column in an index.

2 Answers 2

102

Usually you get this error when you use a VARCHAR(Max) try using:

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

where n is between 1 and 450.

Sign up to request clarification or add additional context in comments.

8 Comments

Why the [Column(TypeName = "VARCHAR")] attribute?
@Zero3 nvarchar is unicode (2bytes/char), and varchar is not (1byte/char). So in case your field does not require different languages (codepages) you can have twice the space.
@TalalYousif if you defined VARCHAR you can select 1 < n < 900.
@TomerW So in other words, the Column attribute is irrelevant to the answer?
@Zero3 not directly, the short answer is that Keys are allowed up to 900byte length...
|
5

If you use EntityTypeConfiguration aka mappings :

public class MyPocoEntitiyTypeConfig<T> : EntityTypeConfiguration<T> where T:class
{

}

public class MyPocoEnt
{
    public virtual string MyProp { get; set; }
}

public class MyPocoEntMapping : MyPocoEntitiyTypeConfig<MyPocoEnt>
{
    public MyPocoEntMapping()
    {
            Property(x => x.MyProp).HasMaxLength(300);
            Property(x => x.MyProp).HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("MyProp") { IsUnique = true }));
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.