petko_stankoski
petko_stankoski

Reputation: 10723

Creating a db in runtime

Untill now I have used this code for creating a db dynamically:

var db = new MyEntities(db_name);
if (!db.DatabaseExists()) 
{
    db.CreateDatabase();

where MyEntities extends the ObjectContext class.

In my new application I have the same code, but now MyEntities extends the DbContext class and the DatabaseExists() and CreateDatabase() are not available.

How can I create a db now?

Upvotes: 1

Views: 139

Answers (1)

Callum Linington
Callum Linington

Reputation: 14417

So the below code will execute a different stategy for creating a database, I believe it will run when a DbContext gets hit. so like using (var context = new DbContext())

Database.SetInitializer(new DropCreateDatabaseAlways<DbContext>());
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DbContext>());
Database.SetInitializer(new CreateDatabaseIfNotExists<DbContext>());

These are pretty self explanatory. You can even override them so that you can add Seed data.

Put this in your Global.asax

As you can see, these are strongly typed classes. They take your inherited DbContext class.

So for instance:

public class BlogContext : DbContext {}

Database.SetInitializer(new DropCreateDatabaseAlways<BlogContext>());

That above code will drop and create the database always using the BlogContext as a reference.

Upvotes: 2

Related Questions