'Add-Migration not adding column to existing table in Entity Framework Core

I am trying to add a new column to my existing table in database, i am specifying new field into class and running Add-Migration command but everytime it is creating a migration class for whole table with CreateTable method instead of AddColumn. Below is the class and generated migration class codes.

public class UserSetup
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public bool Age{ get; set; } // New Field Added

    }

But for new field it is creating migration class for full table as shown below:

public partial class AddUserSetup_1 : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "UserSetup",
                columns: table => new
                {
                    Id = table.Column<int>(nullable: false)
                        .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                    Name= table.Column<string>(nullable: false),
                    Age= table.Column<int>(nullable: false),
                 },
                constraints: table =>
                {
                    table.PrimaryKey("PK_UserSetup", x => x.Id);
                });

       }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "UserSetup");
        }
    }

Also in Add-Migration it is giving me the following error but even migration class is getting created.

System.UnauthorizedAccessException: Access to the path 'C:\Projects\PSM\Portal\src\Portal\Migrations\ApplicationDbContextModelSnapshot.cs' is denied.



Solution 1:[1]

Comment your new Age field

//public bool Age{ get; set; } // New Field Added

Open the "Server Explorer" window and make sure you can see your table in "Data Connections"

Run in Package Manager Console:

  1. Enable-Migrations
  2. Add-Migration InitialCreate –IgnoreChanges
  3. Update-Database

Now EF should recognize your DB Now uncomment your new "Age" field

Run in Package Manager Console:

  1. Add-Migration AddUserSetup_1
  2. Update-Database

Comment: When you write "Enable-Migrations" maybe you will need to add -Force like that:

Enable-Migrations -Force

Solution 2:[2]

This can happen if you don't have the { get; set; } accessors. Clearly not the case in your code example, though.

Solution 3:[3]

If you are using TFS make sure to checkout for edit your 'ApplicationDbContextModelSnapshot.cs' file. It will work just fine!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Eran.G
Solution 2 Sean
Solution 3 Daniel Dantas