Suneel Dixit
Suneel Dixit

Reputation: 889

DbContext trying to create tables

I have a custom DbContext class. I have existing tables in the system. I have setup a POCO based system.

When I try to query the DbSet for a table, then it tries to create the table. Now the table already exist in the DB, sql server will throw exception.

How to suppress creation of tables via EF?

Upvotes: 1

Views: 3170

Answers (2)

nrodic
nrodic

Reputation: 3021

Put this in your DbContext implementation:

// static constructor
static MyDbContext()
{
    Database.SetInitializer<MyDbContext>(null);
}

Upvotes: 1

Amir
Amir

Reputation: 9627

When application is starting (e.g. Application_Start() method of global.asax.cs) instruct the strategy you want to use for db creation:

 Database.SetInitializer(new DropCreateDatabaseIfModelChanges<YourContext>());

Database is in System.Data.Entity namespace.

In case of using new DropCreateDatabaseIfModelChanges<YourContext>() it'll drop the database and try to create that if there is a change between db schema and POCOs.

Upvotes: 2

Related Questions