我是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相信我希望该名称是复合主键的一个组件,也不认为它是实际的主键键。
所以我的问题是:为什么我不能在字符串类型的列上添加索引,如何确保给定列的唯一性(唯一性?)?谢谢。
正如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
。尝试为Index
的Name
定义一个名称。我不确定这是否有效,但值得一试。
更多信息可以在MSDN website找到。