【问题标题】:Generating id for Guid-keyed IdentityUser为 Guid-keyed IdentityUser 生成 id
【发布时间】:2014-08-05 08:00:57
【问题描述】:

我已将默认 MVC5 模板修改为使用 Guids/uniqueidentifiers,而不是使用 string/nvarchar-keyed 用户。我的解决方案与此处讨论的类似:http://blogs.msdn.com/b/webdev/archive/2013/12/20/announcing-preview-of-microsoft-aspnet-identity-2-0-0-alpha1.aspx

我更改了适用的类型参数,但我的第一个用户生成的 id 为 00000000-0000-0000-0000-000000000000。无法创建第二个用户,因为它的主键与第一个用户的主键冲突。

然后,我将适用的类型参数从 Guid 更改为 int,然后它就起作用了,用户 ID 从 1 开始并递增。

那么如何让它与Guid 一起工作?

我只需要挂在某个地方并为每个新创建的用户分配一个新的 Guid。最好的地方在哪里?我想也许在 ApplicationUser (implements IdentityUser) 构造函数中,但我不确定。

【问题讨论】:

  • 您需要确保将 Guid 字段标记为 Identity 字段,否则 EF 不会自动生成 ID。使用数据库优先很容易做到这一点,但我不确定 Code-First 的等价物是什么。
  • 看起来你会使用这些注释:[Key][DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
  • 不会自动为您生成 Guid。您需要自己生成它,否则它将具有它的默认值,即全为零。
  • 是的,我可以看到,但我应该在何时何地进行?
  • 您需要使用@ 符号与我联系。这样我就会收到您的回复的通知。 ;) 您应该调用数据库脚本 NEWID() 或使用 Guid.NewGuid() 在数据层代码中生成 guid。

标签: c# asp.net asp.net-mvc asp.net-identity-2


【解决方案1】:

我发现 Tieson T 的评论代表了正确的答案,但它是作为评论发布的,而不是答案,所以我将在此处重现我的具体解决方案。在我的ApplicationUser 类(实现IdentityUser)中,我覆盖了Id 属性并添加了System.ComponentModel.DataAnnotations.KeyAttributeSystem.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOptionAttribute 属性。因此,我的 applicationUser 类如下所示:

public class ApplicationUser : IdentityUser<Guid, CustomUserLogin, CustomUserRole, CustomUserClaim>
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public override Guid Id
    {
        get { return base.Id; }
        set { base.Id = value; }
    }
    ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-11
    • 1970-01-01
    • 1970-01-01
    • 2019-09-24
    • 1970-01-01
    • 1970-01-01
    • 2014-07-03
    相关资源
    最近更新 更多