【问题标题】:Creating string index with Code first首先使用代码创建字符串索引
【发布时间】:2015-02-25 12:48:36
【问题描述】:

我使用的是 Entity Framework 6.1 代码优先,我的域模型如下。

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

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

表 'dbo.Items' 中的列 'CreatedBy' 的类型不能用作索引中的键列。

【问题讨论】:

    标签: c# sql-server performance entity-framework indexing


    【解决方案1】:

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

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

    其中 n 介于 1 和 450 之间。

    【讨论】:

    • 正如Talal Yousif 所说,当您使用 VARCHAR(Max) 时会出现此错误,但您可以通过仅添加 StringLength 属性来解决此问题。 [StringLength(n)] [Index] public string CreatedBy { set;得到; }
    • 为什么是[Column(TypeName = "VARCHAR")] 属性?
    • @Zero3 nvarchar 是 unicode (2bytes/char),而 varchar 不是 (1byte/char)。因此,如果您的字段不需要不同的语言(代码页),您可以有两倍的空间。
    • @TalalYousif 如果你定义了VARCHAR,你可以选择1 < n < 900
    • @TomerW 所以换句话说,Column 属性与答案无关?
    【解决方案2】:

    如果您使用 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 }));
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-02
      • 1970-01-01
      • 1970-01-01
      • 2020-10-08
      • 2017-03-11
      • 2018-09-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多