在 Entity Framework 代码优先方法中定义唯一键

Define an Unique Key in Entity Framework code-first approch

我正在尝试在 Entity Framework 中定义唯一键约束。

Author table 中 Last_Name 属性 的唯一键。

我正在使用 Entity Framework 6.0 版。

  1. This answer 使用 Data Annotations
  2. 引导我找到那个
  3. This answer 显示 在上下文 class
  4. 中使用 SQL 命令

尝试这样做是最简单的方法。所以我更喜欢数据注释,但我收到了这个错误:

System.Data.SqlClient.SqlException: Column 'Last_Name' in table 'dbo.Authors' is of a type that is invalid for use as a key column in an index.

代码:

public class Author
{
    public Author()
    {
    }

    [Key]
    public int Auth_Id { get; set; }

    public string First_Name { get; set; }  

    [Index("IX_FirstAndSecond", 1, IsUnique = true)]
    public string Last_Name { get; set; }

    public string Biography { get; set; }
}

最有可能的问题在于,默认情况下,EF 代码优先会将所有字符串字段放入数据库中的 VARCHAR(MAX) - 无法索引(因为它的大小超过 900 字节).

您可能只需要定义一个 字符串长度 (对于 all[= 这将是一个 好主意 24=] 你的字符串字段!):

public class Author
{
    public Author()
    {
    }

    [Key]
    public int Auth_Id { get; set; }

    [StringLength(100)]
    public string First_Name { get; set; }  

    [Index("IX_FirstAndSecond", 1, IsUnique = true)]
    [StringLength(100)]
    public string Last_Name { get; set; }

    public string Biography { get; set; }
}

所以现在你的 First_NameLast_Name 列应该是数据库 table 中的 VARCHAR(100),并且应该很好地应用索引。