【问题标题】:Custom Fields for IdentityUserIdentityUser 的自定义字段
【发布时间】:2015-07-27 20:02:44
【问题描述】:

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

    // 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. 最后,如果我想将 IPAddress 存储为 VARBINARY 或 BINARY,该怎么办?这甚至不是 C# 将接受的数据类型。

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

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

    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 版。

谢谢

【问题讨论】:

    标签: asp.net-identity-2


    【解决方案1】:

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

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

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

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

    3) 要获得BINARY,您需要使用byte[] 输入C#。 (参考:https://stackoverflow.com/a/1158670/809357

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

    当您更改数据模型时,您可以通过add-migration NewMigrationName 创建新迁移或通过update-database -Target PreviousMigrationName 将数据库回滚到以前的迁移状态,然后通过add-migration ExistingMigrationName -Force 重新生成现有迁移,然后执行Update-database

    【讨论】:

    • 太棒了!这似乎很容易解决了所有问题。由于我已经搞砸了迁移,因此我回滚到 InitialCreate 迁移,这似乎完全撤消了我手动执行的所有操作。然后我删除了我手动更改的迁移cs文件,我不再使用它了。我对 ApplicationUser 中的字段进行了更改,然后添加了一个新的迁移,这次它正确地设置了数据库中的约束。我是否正确执行了该过程?如果是这样,这真的很容易做到。 Identity 和 EntityFramework 太棒了!
    • 听起来你做得很好而且正确。很高兴它对你有用!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-06
    相关资源
    最近更新 更多