Search code examples
c#entity-frameworkasp.net-identity

Can I generate UserId for Entity Framework AspNet Identity manually?


I need to generate new Guid value myself. Currently I created helper table with this structure:

(id, aspnet_id)

And whenever I need to get a User or list of users, I have to join those two tables.

Can I tell Entity Framework Identity Manager to not generate new Guids but to use generated-by-me value?


Solution

  • You are right, the guid is not generated in the database. If you take a look at the table you'll notice that the field doesn't have a default value.

    Besides that, with Entity Framework database values have to be set in the constructor of the class. If not, the default value of the database is overwritten, except for keys (autonumbers) and fields that exist in the database but are not known to the model.

    So if you create a new IdentityUser, the Id is set with a Guid. But you can overwrite the value:

    var appUser = new IdentityUser
    {
        UserName = model.Email,
        Email = model.Email,
        Id = "the desired guid"
    };
    var identityResult = await userManager.CreateAsync(appUser, model.Password);
    

    Regardless how you add the user, using the userManager or directly, this will work. So the answer is, yes you can.

    As a sidenote, you can also extend the IdentityUser to add fields:

    public class ApplicationUser : IdentityUser
    {
        [Required]
        public int aspnet_id{ get; set; }
    
        public DateTime? LastLogin { get; set; }
    }