Dishant
Dishant

Reputation: 1595

Unable to create SQL Table using code first approach in Azure via Entity Framework

I am trying to publish my database into azure using EF but am not able to see any tables after migration.

I tried below commands:

Add-Migration MyTables
Update-Database

When I check my Azure DB trough SSMS, I can see logs for all the migration in dbo.__EFMigrationsHistory table, but no table is getting created.

My Context Class:

 public class ApplicationContext : DbContext
{
    public DbSet<Expense> Expenses { get; set; }

    public ApplicationContext(DbContextOptions opts) : base(opts)
    {

    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
    }
}

ConnectionString:

"ConnectionString": { "ExpenseApplicationDB": "Server=tcp:myserver,1432;Initial Catalog=ExpenseDatabase;Persist Security Info=False;User ID={your_username};Password={your_password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;" }

Also in publish dialog in database section it showing 'No databases found in the project'.

If I try to achieve same thing using local DB than it's working as expected. Is there anything that am doing wrong?

Upvotes: 2

Views: 1102

Answers (1)

Joey Cai
Joey Cai

Reputation: 20127

When you publish with .net EntityFramework, you could click the tab Execute Code First Migration(runs on application start).

However, in EF core, it does not exist it. Additionally, EF does not support Automatic migrations, you may need to manually execute Add-Migration for adding migration files.

Also in publish dialog in database section it showing 'No databases found in the project'.

You also could not exist the database, you could not apply migration on publish.

enter image description here

If you want to apply migration at runtime, you could add the following code int the Configure method of Startup.cs.

 using (var scope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
    {
        scope.ServiceProvider.GetRequiredService<ApplicationDbContext>().Database.Migrate();
    }

For more details, you could refer to this thread.

Note, you need to ensure that you could connect to azure database. You could set the connection in azure to the vs local. So that you could also test with azure database in local and debug it.

Upvotes: 0

Related Questions