FernandoPaiva
FernandoPaiva

Reputation: 4460

How to create all tables on database when application is loading?

I'm learning about Entity Framework and I want to create a project with it. I've use FluentNhibernate in my project but now I want to try Entity, but I have a doubt about how to create all tables(DBSet) when the application is loading. In my case I have 3 tables: Cliente, Produto, Venda, that I want to create when application is loading but I don't know how to do this.

How could I do this ?

trying

[DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]
public class DatabaseContext : DbContext{
    public DatabaseContext():base("default"){
        Database.SetInitializer<DatabaseContext>(new CreateDatabaseIfNotExists<DatabaseContext>());
        //Database.CreateIfNotExists();                
    }

    public DbSet<Cliente> clientes { get; set; }
    public DbSet<Produto> produtos { get; set; }
    public DbSet<Venda> vendas { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder){        
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

        modelBuilder.Entity<Produto>()
                    .Property(p => p.valor)
                    .HasPrecision(9,2); // or whatever your schema specifies

        Database.SetInitializer<DatabaseContext>(null);
        base.OnModelCreating(modelBuilder);
    }
}

Upvotes: 0

Views: 66

Answers (2)

Embri
Embri

Reputation: 622

In the OnModelCreating method remove:

Database.SetInitializer<DatabaseContext>(null);

i suggest you to read: http://www.entityframeworktutorial.net/code-first/database-initialization-strategy-in-code-first.aspx

and about automatic migration: http://www.entityframeworktutorial.net/code-first/automated-migration-in-code-first.aspx

Upvotes: 1

Richard Padre
Richard Padre

Reputation: 141

Assuming you already have all your DbContext and Entities setup and you are just asking about generating/updating the database, you are looking for Entity Framework's migration features.

Open Package Manager Console and run the following commands in your project:

// Enable migrations to your project
Enable-Migrations

// Add migrations to your project
Add-Migration

// Update any changes to the generated database
Update-Database

More details here: https://martinnormark.com/entity-framework-migrations-cheat-sheet/

Upvotes: 1

Related Questions