【发布时间】: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 创建迁移并更新数据库。
我的问题是这样的:
- 如何设置 RegistrationDate 的默认值?我希望它是 SQL Now()。迁移后我可以在数据库中进行更改,但这会使我的代码和数据库不同步。
- 在 IPAddress 上,我希望最大大小为 39 个字符。当我更新数据库时,该字段被创建为 NVARCHAR(MAX) NULL。我希望它是 NVARCHAR(39) NOT NULL。我在 IdentityUser 中看不到这样做。
- 最后,如果我想将 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 版。
谢谢
【问题讨论】: