Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/apache-kafka/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 先用代码创建字符串索引_C#_Sql Server_Performance_Entity Framework_Indexing - Fatal编程技术网

C# 先用代码创建字符串索引

C# 先用代码创建字符串索引,c#,sql-server,performance,entity-framework,indexing,C#,Sql Server,Performance,Entity Framework,Indexing,我首先使用EntityFramework6.1代码,下面是我的域模型 class Item { [Index] public string CreatedBy { set; get; } } 当我使用更新数据库进行迁移时,出现以下错误。然而,据我所研究,[Index]应该作为字符串的注释 表“dbo.Items”中的列“CreatedBy”的类型无效,无法用作索引中的键列 通常在使用VARCHAR(Max)时会出现此错误,请尝试使用: [Column(TypeName = "

我首先使用EntityFramework6.1代码,下面是我的域模型

class Item
{
    [Index]
    public string CreatedBy { set; get; }
} 
当我使用更新数据库进行迁移时,出现以下错误。然而,据我所研究,
[Index]
应该作为
字符串的注释

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


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

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

其中n介于1和450之间。

如果使用EntityTypeConfiguration映射:

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 }));
        }
    }
}
公共类MyPoCoEntityTypeConfig:EntityTypeConfiguration其中T:class
{
}
公共类MyPocoEnt
{
公共虚拟字符串MyProp{get;set;}
}
公共类MyPocoEntMapping:MyPoCoEntityTypeConfig
{
公共MyPocoEntMapping()
{
属性(x=>x.MyProp).HasMaxLength(300);
属性(x=>x.MyProp).HasColumnAnnotation(“Index”,newIndexAnnotation(“MyProp”){IsUnique=true});
}
}
}

如前所述,使用VARCHAR(Max)时会出现此错误,但可以通过仅添加StringLength属性来修复此错误。[StringLength(n)][Index]公共字符串由{set;get;}创建为什么
[Column(TypeName=“VARCHAR”)]
属性?@Zero3 nvarchar是unicode(2字节/字符),而VARCHAR不是(1字节/字符)。因此,如果您的字段不需要不同的语言(代码页),您可以使用两倍的空格。@Talalyous如果您定义了
VARCHAR
,您可以选择
1
@TomerW,那么换句话说,
属性与答案无关?