代码之家  ›  专栏  ›  技术社区  ›  Virus721

实体框架-字符串列上的唯一约束

  •  1
  • Virus721  · 技术社区  · 7 年前

    我是EF(6.2)的初学者,我正在尝试使用代码优先的方法生成一个数据库。

    我的一些实体有一个字符串属性,它应该是唯一的,比如用户名或文章的标题。

    为了确保唯一性,我添加了一个索引,指定列应该是唯一的:

    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    
    namespace Blog.Models
    {
        public class User
        {
            [Key, Index, Required]
            public int Id { get; set; }
    
            [Index(IsUnique = true), Required]
            public string Name { get; set; }
    
            [Required]
            public string Password { get; set; }
    
            public ICollection<Comment> Comments { get; set; }
        }
    }
    

    但是它会抱怨,因为我试图在字符串类型的列上添加索引,而它接受在整数列上使用索引,例如行ID。

    Key 属性,但我已经在使用它来定义主键了,我不想让EF认为我希望名称是复合主键的一个组件,也不想把它看作实际的主键。

    所以我的问题是 :为什么不能在字符串类型的列上添加索引?如何确保唯一性给定列的?非常感谢。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Vlădel    7 年前

    正如MSDN教程中所写, Indexes 在上是可能的 strings

    public class User
        {
            public int UserId { get; set; }
    
            [Index(IsUnique = true)]
            [StringLength(200)]
            public string Username { get; set; }
    
            public string DisplayName { get; set; }
        }
    

    可能因为你使用 Index 上面没有名字 Id ,也是一个 索引 Name . 尝试定义 索引 . 我不确定这是否有效,但值得一试。

    更多信息请点击 MSDN website .

    推荐文章