Search code examples
c#asp.netasp.net-mvcasp.net-identity-2

Generating id for Guid-keyed IdentityUser


I have modified the default MVC5 template to, rather use than string/nvarchar-keyed users, to use Guids/uniqueidentifiers. My solution was similar to the one discussed here: http://blogs.msdn.com/b/webdev/archive/2013/12/20/announcing-preview-of-microsoft-aspnet-identity-2-0-0-alpha1.aspx

I changed the type parameters where applicable, but my first user was generated with an id of 00000000-0000-0000-0000-000000000000. The second user could not be created because its primary key conflicted with that of the first.

I then changed the applicable type parameters from Guid to int, and then it worked, with user ids starting at 1 and incrementing.

So how do I get it to work with Guid?

I just need to hook in somewhere and assign each newly created user a new Guid. Where is the best place to do this? I thought maybe in the ApplicationUser (implements IdentityUser<Guid, ...>) constructor, but I was unsure.


Solution

  • I found that Tieson T's comment represented the correct answer, but it was posted as a comment, rather than an answer, so I'll reproduce my specific solution here. In my ApplicationUser class (implements IdentityUser), I overrode the Id property and added the System.ComponentModel.DataAnnotations.KeyAttribute and System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOptionAttribute attributes. My applicationUser class thus looks like this:

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