【问题标题】:Specify max length when declaring string field key with the Entity Framework 6.1 IndexAttribute attribute?使用 Entity Framework 6.1 IndexAttribute 属性声明字符串字段键时指定最大长度?
【发布时间】:2014-03-29 13:58:21
【问题描述】:

我有一个实体框架模型(类),我想将它用作关键字段的字符串属性。我试过这样定义属性:

[IndexAttribute("SourceText", IsUnique=true)]
public string SourceText { get; set; }

这会导致 SQL 运行时错误,提示该属性无法用作键字段。我理解为什么,因为唯一键不能超过 8000 个字符,而字符串字段可能比这长得多。那么,有没有办法告诉 EF 我不需要超过要用作键的字段的前 500 个字符?

【问题讨论】:

标签: c# sql entity-framework indexing


【解决方案1】:

如果您使用 StringLengthAttribute 数据注释来指定您尝试索引的字符串列的最大长度,这可能会起作用:

[Index("SourceText", IsUnique = true), StringLength(500)]
public string SourceText { get; set; }

但是,我不完全确定这是最好的解决方案。我不太了解,但显然你可以include large columns as part of a non-clustered index

您可以在非聚集索引中包含非键列,以避免当前的索引大小限制,即最多 16 个键列和最大 900 字节的索引键大小。 SQL Server 数据库引擎在计算索引键列的数量或索引键列的总大小时不考虑非键列。

在包含列的非聚集索引中,索引键列的总大小限制为 900 字节。所有非键列的总大小仅受 INCLUDE 子句中指定的列大小的限制;例如,varchar(max) 列限制为 2 GB。 INCLUDE 子句中的列可以是所有数据类型,除了 textntextimage

但我不知道如何使用数据注释或Fluent API 来做到这一点。

在非聚集索引中包含大列的额外资源

  1. How to resolve 900 key length limit index on the column which have datatype varchar(4096) in SQL Server 2005?
  2. 900 byte index size limit in character length
  3. Create Indexes with Included Columns

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    • 2016-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多