Vahe
Vahe

Reputation: 1841

Entity Framework Code First (New Database) Producing Error - "CREATE DATABASE permission denied in database 'master'."

I have created a new project (ASP.NET MVC) that will use Entity Framework Code First to create a new Database and add records to the database one time only and populate a drop down. I am trying to figure out how to generate the database automatically. So far, when I run the code I get "CREATE DATABASE permission denied in database 'master'.". Master is not the correct database. What would I need to modify in my code or connection string to create the database automatically from scratch?

Controller:

namespace TDReport.Controllers
{
    public class ReportController : Controller
    {
        //
        // GET: /Report/

        public ActionResult Index()
        {
            var db = new StageContext();
            if (!db.Database.Exists())
            {
                db.Database.Create();
                db.Stages.Add(new Stage { PCR = 201 });
                db.Stages.Add(new Stage { PCR = 202 });
                db.Stages.Add(new Stage { PCR = 203 });
                db.Stages.Add(new Stage { PCR = 501 });
                db.SaveChanges();
            }
            return View();
        }

Context Class:

namespace TDReport.Models
{
    public class StageContext : DbContext
    {
        public DbSet<Stage> Stages { get; set; }
        public DbSet<Report> Reports {get; set;}
    }
}

Model:

namespace TDReport.Models
{
    public class Stage
    {
        public int ID { get; set; }
        public int PCR { get; set; }
    }
}

Connection String Tags:

<connectionStrings>
    <add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-TDReport-20140825134744;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-TDReport-20140825134744.mdf" />
    <add name="StageProductionEntities" connectionString="metadata=res://*/Models.Model1.csdl|res://*/Models.Model1.ssdl|res://*/Models.Model1.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\StageProduction.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>

Upvotes: 0

Views: 984

Answers (1)

Yuliam Chandra
Yuliam Chandra

Reputation: 14640

You need to have a connection string that matches the name of db context if you have parameterless constructor in the db context.

<add name="StageContext" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=TheDatabaseName;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\TheDatabaseName.mdf" />

Upvotes: 1

Related Questions