ASP.NET-Identity限制UserName长度

时间:2014-02-23 22:47:21

标签: entity-framework ef-code-first username entity-framework-6 asp.net-identity

如何限制表UserName中的AspNetUsers字段?

这两个都没有:

public class ApplicationUser : IdentityUser
{
    [Required, MaxLength(15)]
    public string UserName { get; set; }

}

或者这个:

modelBuilder.Entity<ApplicationUser>().Property(x => x.UserName).HasMaxLength(15);

作品。

我需要这个,因为在Index上设置nvarchar(max)会给我这个错误信息:

  

列&#39;用户名&#39;在表格中,dbo.AspNetUsers&#39;是一种类型   无效用作索引中的键列。

为了详细,我试图像这样设置索引:

public override void Up()
{
    CreateIndex("dbo.AspNetUsers", "UserName", true, "IX_UserName");
}

public override void Down()
{
    DropIndex("dbo.AspNetUsers", "IX_UserName");
}

3 个答案:

答案 0 :(得分:5)

在今天发布的最新版本中,这应该可以解决问题:

modelBuilder.Entity<ApplicationUser>().Property(x => x.UserName).HasMaxLength(15);

答案 1 :(得分:0)

试试这个

public class ApplicationUser : IdentityUser
{
    [Required, MaxLength(15)]
    public override string UserName { get; set; }

}

答案 2 :(得分:0)

很多时间过去了,但我认为有人可能仍然觉得它很有用。我遇到了同样的问题,并在此处找到了解决方案的线索。 迁移机制忽略MaxLength属性,但可以手动添加更正:

public override void Up()
{
    AlterColumn("dbo.AspNetUsers", "UserName", c => c.String(nullable: false, maxLength: 15, storeType: "nvarchar"));
    CreateIndex("dbo.AspNetUsers", "UserName");
}

public override void Down()
{
    DropIndex("dbo.AspNetUsers", new[] { "UserName" });
    AlterColumn("dbo.AspNetUsers", "UserName", c => c.String(nullable: false, maxLength: 256, storeType: "nvarchar"));
}

update-database字段缩短后,按UserName搜索的SQL查询运行得更快(至少使用我使用的mySQL),因为索引用于高效搜索。

相关问题