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

问题描述 投票:1回答:1

我是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相信我希望该名称是复合主键的一个组件,也不认为它是实际的主键键。

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

c# asp.net entity unique data-annotations
1个回答
1
投票

正如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,以及在Index上没有任何名字的Name。尝试为IndexName定义一个名称。我不确定这是否有效,但值得一试。

更多信息可以在MSDN website找到。

© www.soinside.com 2019 - 2024. All rights reserved.