如何在实体中使用 Table 创建 PK 和唯一用户名(使用代码优先)?

How to create PK and Unique Username at Use Table in Entity (Using Code-first)?

我想设置如下。
我正在使用最新的 Entity framework 代码优先方法..

Public class AppUser
{
        [Key]
        public int Id { get; set; }
        [Required]
        [Index(IsUnique = true)]
        public string UserName { get; set; }
}

但是它不起作用..

示例记录如下

收到以下错误消息:

"exceptionmessage": "Column 'UserName' in table 'dbo.ApplicationUser' is of a type that is invalid for use as a key column in an index.",

您需要限制 UserName 属性 的长度。为此使用 StringLength 注释。

If the size of all fixed key columns plus the minimum size of all variable columns specified in the CREATE INDEX statement exceeds 900 bytes, the CREATE INDEX statement fails.

来源:http://msdn.microsoft.com/en-us/library/ms191241.aspx

将此添加到您的实体

[Required]
[Index(IsUnique = true)]
[StringLength(50)]
public string UserName { get; set; }

StringLength(50) 将列的大小设置为 50 个字符。没有它,代码创建的列首先是 NVARCHAR(MAX) 类型,EF 无法在这种列上创建索引