Code first with no create DB permissions on the server

The hosting services or the production database servers do not give create db rights to the app for a lot of reasons. So, when our code first MVC app gets deployed it does not work as it tries to create a database.

There are a lot of posts about code first with existing database. They often get too much into class structure for the models and how looks like on db. The solution of this is too burried or not there at all. So I decided to post about only this issue.

In order to handle this, we need to make it use the existing database and we also need the schema.

Here's how I accomplished it:

I used a computer store as an example. As it sells computers(do we even use that word), I created a model as

public class Computer
{
[Required]
public int Id { get; set; }

 public string Name { get; set; }

 [AllowHtml]
 [DataType(DataType.MultilineText)]
 public string Descr { get; set; }

 public string Type { get; set; }

 public Decimal Price { get; set; }
}

Then I created a controller for the with a new db context as CompStore. The db context is the key here and it looks like:

public class CompStoreDBContext : DbContext
{

public CompStoreDBContext(): base("name=DefaultConnection")
{
    
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{

}
 
 public DbSet Computers { get; set;  }

}

Notice the constructor. It inherits from the base and the connection string name is passed to it.

If there's something special we need to such as define table names on in DB, we can use OnModelCreating event. Here, I left it alone.

Now, it uses the database passed in the connection string but it still doesnt have the schema. Sometimes we dont even have DDL rights.

No issues MVC4 migrations made this all easy. I will show it in nextpost.