1

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?

toy
  • 422
  • 1
  • 7
  • 19
  • 1
    "the default vals for these custom props should just pop in right" - Assuming this is all backed by an Entity Framework DbContext, then no. You have to change the mapped property to one of the StoreGeneratedPattern values - I usually change it to Identity. – Tieson T. Jun 27 '18 at 01:51
  • 1
    Shot in the dark here but just to confirm: // Add custom user claims here userIdentity.AddClaim(new Claim("companyId", this.groupId.ToString()));... Is this meant to be group id or company id? – Kowalchick Jun 27 '18 at 01:53
  • @Mitchell - yes except i made a type - updated now.... – toy Jun 28 '18 at 04:27

1 Answers1

1

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

toy
  • 422
  • 1
  • 7
  • 19