EntityFrameworkCore no longer creating entities

35 Views Asked by At

Entity Framework Core 2.2.0 | Visual Studio 2019

When I first ran this code it created objects in my SQL Server Express database under dbo schema :

public class MyTable
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class MyContext : DbContext
{
    public DbSet<MyTable> MyTables { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        base.OnConfiguring(optionsBuilder);

        optionsBuilder.UseSqlServer('connection string to sql server express');
    }
}

using (var context = new MyContext ())
{
    context.Database.EnsureCreated();
}

Next I went to SSMS and manually deleted MyTable.

Now when I run the same code it doesn't create MyTable.

A logical explanation is that EFC uses tracking tables that indicates MyTable still exists and so it doesn't attempt to create it.

But I can't find any such tracking tables.

What is the explanation?

2

There are 2 best solutions below

2
tmaj On

EF run the migration that created the table so it assumes the table is there.

If you add a new migration it will likely contain the code to create the table again. Please note this will lead to two migratons that create the same table and lead to trouble when running on an empty database.

If you delete tables not via EF then you are no longer in the code-first scenario.

Your best option may be to recreate the database. This will delete data.

If you cannot afford to lose data then recreate the table directly in the db (or restore from backup which has the table still in. Finally, there is a path with the migration history table but It may be complicated depending on specific details.

0
John Meek On

goto the package manager console in visual 2019

type)

add-migration migrationname
update-database