Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework is trying to create a database, but its not what I want

I have a small asp.net mvc4 application (working fine in my local machine), that uses entity framework v4.1.0.0 with ADO.net DbContext Generator.(SQL Server 2008 r2)

I am adding newer versions of dlls required through the "Add Deployable Dependencies..." context menu in Visual Studio 2010.

I have a shared hosting with godaddy.com, I have uploaded the files to server and created the database, now here comes the problem.When I try to browse my site I get the following error:

CREATE DATABASE permission denied in database 'master'.

I looked this up around and found out that this error was caused by EF code first trying to create database.but i do not want EF code first to recreate the database, how do i turn off this automatic database creation altogether? I have no intentions of using the code-first feature whatsoever.

Please help.

like image 802
nthapa Avatar asked Mar 07 '12 09:03

nthapa


2 Answers

put this code into the Application_Start() method of Global.asax or constructor on your DbContext class

Database.SetInitializer<MyContext>(null);

If you want to recreate database when POCO domains are changed, use following code instead of above

Database.SetInitializer<MyContext>(new DropCreateDatabaseIfModelChanges<MyContext>());
like image 50
Ray Avatar answered Oct 30 '22 11:10

Ray


If you are using EF Migrations, this is what you set for it:

public sealed class DbConfiguration : DbMigrationsConfiguration<DatabaseContext>
{
    public DbConfiguration()
    {
        AutomaticMigrationsEnabled = false;
    }
}

But this doesn't answer the question on EF Code First itself. If the database already exists, then EF will not try to create it. So you just need to point it to an existing database. And to make sure the connection string name is the same as the name of the database context. If it is not, you need to provide it to it with some overrides:

public class DatabaseContext : DbContext
{
    public DatabaseContext() 
      : base(ApplicationParameters.ConnectionStringName)
    {
    }

    public DatabaseContext(string connectionStringName)
      : base(connectionStringName)
    {
    }

}
like image 37
ferventcoder Avatar answered Oct 30 '22 11:10

ferventcoder