Search code examples
c#asp.net-mvcentity-frameworkasp.net-identity-2

How to properly remove a column from AspNetUsers table that was created during a migration with Package Manager Console?


I added a new table to the identity's database, and I think I messed up because now in the AspNetUsers table I have a new column thats a foreign key to my new table and I don't want that in there. What is the best way to remove that new column?

This is how I started off

public class ApplicationUser : IdentityUser
    {
        ...
        public virtual SuperAdminHistory SuperAdminHistory { get; set; }
    }

This is my class

public class SuperAdminHistory
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int SuperAdminHistoryID { get; set; }

        public string SuperAdminIdCreator { get; set; }

        public string CreatedAdminID { get; set; }

        public string DateCreated { get; set; }

        public string ModifiedBy { get; set; }

        public string ModifiedDate { get; set; }

        public bool IsActive { get; set; }
    }

and then I added this to the ApplicationDbContext : IdentityDbContext

public System.Data.Entity.DbSet<SuperAdminHistory> SuperAdminHistory { get; set; }

I then when into the Package Manager Console and did

Add-Migration "NewTable"

Then...

Update-Database

At first I made a couple mistakes when trying to create a new table, so I am wondering if the earlier mistakes created the foreign key in my AspNetUsers table.

The AspNetUsers table now looks like this AspNetUsers Table

and my new table is now in the database.


Solution

  • When you add a navigation property, it creates a relationship and EF will add a foreign key. If you don't want that, do:

    [NotMapped]
    public virtual SuperAdminHistory SuperAdminHistory { get; set; }
    

    or add the fluent mapping: .Ignore(p => p.SuperAdminHistory);

    If you make that change and apply a migration it should remove the field. Another option is to rollback your prior migration:

    Update-Database -TargetMigration:"name_of_migration"