首先使用Code创建字符串索引

Dar*_*der 37 c# sql-server indexing performance entity-framework

我正在使用Entity Framework 6.1代码优先,我的域模型如下.

class Item
{
    [Index]
    public string CreatedBy { set; get; }
} 
Run Code Online (Sandbox Code Playgroud)

当我使用update-database进行迁移时,我收到以下错误.但是,据我所研究,[Index]应该作为注释string.

表'dbo.Items'中的列'CreatedBy'的类型无效,无法用作索引中的键列.

Tal*_*sif 86

通常,当您使用VARCHAR(Max)尝试使用时会出现此错误:

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

其中n介于1和450之间.

  • 为什么`[Column(TypeName ="VARCHAR")]`属性? (4认同)
  • @ Zero3 nvarchar是unicode(2bytes/char),而varchar不是(1byte/char).因此,如果您的字段不需要不同的语言(代码页),您可以拥有两倍的空间. (3认同)
  • @TalalYousif如果定义了`VARCHAR`,你可以选择`1 <n <900`. (3认同)
  • @TomerW换句话说,`Column`属性与答案无关? (2认同)

Ogn*_*rov 5

如果您使用EntityTypeConfiguration aka映射:

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 }));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)