Creating string index with Code first

c# entity-framework indexing performance sql-server

Question

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.

1
37
9/13/2016 6:34:24 PM

Accepted Answer

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.

91
12/29/2014 11:12:35 AM

Popular Answer

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 }));
        }
    }
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow