简体   繁体   English

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

[英]Entity Framework - Unique constraint on a string column

I'm a beginner with EF (6.2) and I'm trying to generate a database using the code first approach.我是 EF (6.2) 的初学者,我正在尝试使用代码优先方法生成数据库。

Some of my entities have a string property which should be unique, like the name of a user or the title of an article.我的一些实体有一个字符串属性,它应该是唯一的,比如用户名或文章标题。

In order to ensure unicity, I've added an index which specifies that the column should be unique :为了确保唯一性,我添加了一个索引,指定该列应该是唯一的:

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; }
    }
}

However it complains because I'm trying to add an index on a string type column, while it accepts using an index on an integer column, such as the row ID.但是它会抱怨,因为我试图在字符串类型列上添加索引,而它接受在整数列上使用索引,例如行 ID。

I could use the Key attribute, but I'm already using it to define a primary key and I don't want EF to beleive that I want the name to be a component of a composite primary key nor to consider it as the actual primary key.我可以使用Key属性,但我已经在使用它来定义主键,我不希望 EF 相信我希望名称成为复合主键的一个组件,也不想将其视为实际的主键钥匙。

So my question is : Why can't I add an index on a column of string type and how can I ensure the unicity (uniqueness ?) of a given column ?所以我的问题是:为什么不能在字符串类型的列上添加索引,如何确保给定列的唯一性(唯一性?)? Thank you.谢谢你。

As written in the Tutorial from MSDN, Indexes are possible on strings as they state in the following example code正如 MSDN 的教程中所写的那样,可以在strings上使用Indexes ,正如它们在以下示例代码中所述

public class User
    {
        public int UserId { get; set; }

        [Index(IsUnique = true)]
        [StringLength(200)]
        public string Username { get; set; }

        public string DisplayName { get; set; }
    }

but when it comes to Multiple-Column Indexes, they mention you need to write the order.但是当涉及到多列索引时,他们提到您需要编写顺序。

Probably there's a conflict arising because you use Index without any name on Id , and also an Index without any name on Name .也许有出现,因为你使用冲突Index上没有任何名称Id ,并在Index没有任何名称Name Try defining a name for the Index of the Name .尝试为NameIndex定义一个Name I am not sure if this works, but it's worth a try.我不确定这是否有效,但值得一试。

More info can be found here at the MSDN website .更多信息可以在MSDN 网站上找到

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM