我是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认为我希望名称是复合主键的一个组件,也不想把它看作实际的主键。
所以我的问题是
:为什么不能在字符串类型的列上添加索引?如何确保唯一性给定列的?非常感谢。