IdentityUser 的自定义字段

Custom Fields for IdentityUser

我正在尝试为我的 IdentityUser 添加自定义字段。我已经阅读了文档以及我在网上找到的几篇文章。我能够弄清楚如何添加自定义字段,但我不确定如何对它们设置约束。 None 我找到的文章中涵盖了这个主题。

    // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
    public DateTime RegistrationDate { get; set; }

    public string IPAddress { get; set; }

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }
}

上面是我的代码示例。我添加了 2 个字段。注册日期和 IP 地址。我使用 PowerShell 创建迁移并更新数据库。

我的问题是:

  1. 如何设置 RegistrationDate 的默认值?我希望它是 SQL Now()。迁移后我可以在数据库中进行更改,但这会使我的代码和数据库不同步。
  2. 在 IPAddress 上,我希望最大长度为 39 个字符。当我更新数据库时,该字段被创建为 NVARCHAR(MAX) NULL。我希望它是 NVARCHAR(39) NOT NULL。反正我在 IdentityUser 中看不到这样做。
  3. 最后,如果我想将 IP 地址存储为 VARBINARY 或 BINARY 怎么办?这甚至不是 C# 接受的数据类型。

创建迁移后,我可以进入迁移文件并进行一些更改,但这些更改不会反映在数据库中。如果我尝试从 PowerShell 重新 运行 更新数据库,我收到一条错误消息,指出没有要更新的更改。

最重要的是。我不知道是否应该手动更新迁移文件,因为它们是生成的代码。

    public partial class IPAddress : DbMigration
{
    public override void Up()
    {
        AddColumn("dbo.AspNetUsers", "IPAddress", c => c.String(nullable: false, maxLength: 39));
    }

    public override void Down()
    {
        DropColumn("dbo.AspNetUsers", "IPAddress");
    }
}

我使用的是 Visual Studio 2015 和 4.6 版。

谢谢

1) 要在 RegistrationDate 上设置默认日期,您需要创建 ApplicationUser 的默认构造函数,将日期设置为您需要的日期:

public ApplicationUser()
{
    RegistrationDate = DateTime.Now();
}

2) 要更改字段的大小,您需要在 IPAddress 字段上应用 [MaxLength(39)] 属性:

 [MaxLength(39)]
 public string IPAddress { get; set; }

3) 要获得 BINARY,您需要在 C# 中使用 byte[] 类型。 (参考:)

4) 您不应手动更改迁移脚本 - 迁移包含数据库的 XML 快照并将该快照保存在 __MigrationsHistory table 中。因此,如果您更改迁移脚本,则不会重新生成快照,EF 也不会获取您的更改。

当您更改数据模型时,您可以通过 add-migration NewMigrationName 创建一个新的迁移,或者通过 update-database -Target PreviousMigrationName 将您的数据库回滚到以前的迁移状态,然后通过 [=21= 重新生成现有的迁移] 然后做 Update-database