Search code examples
asp.netasp.net-mvcentity-frameworkasp.net-identity

How to add column to aspnetuser?


I have a project with 2 databases: 1 where you have aspnetusers, roles logins and so on and 2nd database for the rest of datas. I want to make this project to be separate database per tenant, and would like to be able to change connection string based on users company Id. So in order to do that I need to add a column to aspnetusers table.

So far I have this

    public class ApplicationUser : IdentityUser
{
    public DateTime? LastVisitDate { get; set; }
    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("LastVisitDate", this.LastVisitDate.ToString()));
        userIdentity.AddClaim(new Claim("CompanyId", this.CompanyId.ToString()));
        return userIdentity;
    }
}

public static class IdentityExtensions
{
    public static string GetLastVisitDate(this IIdentity identity)
    {
        var claim = ((ClaimsIdentity)identity).FindFirst("LastVisitDate");
        // Test for null to avoid issues during local testing
        return (claim != null) ? claim.Value : string.Empty;
    }

    public static string GetCompanyId(this IIdentity identity)
    {
        var claim = ((ClaimsIdentity)identity).FindFirst("CompanyId");
        return (claim != null) ? claim.Value : string.Empty;
    }

After this I did the add-migration and it all passed. The problem is on Update-Database. I get an error that 'xxxx.aspusers.aspnetusers' doesn't exist. How do I make it update only 'aspusers.aspnetusers'? It is trying to target a database that is set on Configurations.cs, which is the 2nd database.


Solution

  • How do I make it update only 'aspusers.aspnetusers'?

    You can not force a migration to only apply to one table.

    If you want to define which database your migration apply to, you use -ConnectionString option.

    updata-database -ConnectionString YOUR_CONNECTION_STRING