Search code examples
asp.netasp.net-mvcasp.net-identity

insert IdentityUser with default values and custom properties fails


I'm building on a couple of posts here:

So I've extended my IdentityUser with custom properties; that's all working well. These custom properties are designated in SQL Server as having default values, i.e. if I insert a new user, the default values for these custom props should just pop in, right?

No - they fail with NULL value (since they are designated with NOT NULL), and if I open them up to be not NOT NULL, they fail here (at the AddClaim line),

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
    userIdentity.AddClaim(new Claim("companyId", this.companyId.ToString()));

    return userIdentity;
}

because even though the companyId default val is set in mssql = "newcompanyid", it never sets from NULL and so comes back as NULL.

What am I missing here?


Solution

  • thanks to tieson
    i was able to fix this using this technique:

    http://www.vannevel.net/2015/04/03/how-to-configure-a-custom-identityuser-for-entity-framework/

    with a basis in the following:

    so in the end my code looked like:

    public class ApplicationUser : IdentityUser
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
        public int companyId { 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
            userIdentity.AddClaim(new Claim("companyId", this.companyId.ToString()));
    
            return userIdentity;
        }
    }
    

    hope this helps someone else