Invalid object name when trying to create new table

Viewed 885

Started with EF6 yesterday and am already frustrated.

Anyways, as far my research says, EF can create a database if it doesn't exists and can also create tables. So, i passed my connection string to my DbContext as follows :

public CampaignDbContext() : base("Data Source=xx;Initial Catalog=NewTestDb;User ID=xx;Password=xx;")
{ }

My models and the entire DbContext class is most likely irrelevant here so that's why i am not adding the code. Anyways, my model class is called Campaign and inside the DbContext class, i have declared the obvious :

public DbSet<Campaign> Campaigns { get; set; }

//Also added this
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   Database.SetInitializer<CampaignDbContext>(null);
   base.OnModelCreating(modelBuilder);
}

Now, from my test method, when i populate the Campaigns DbSet and call :

CampaignDbContext.SaveChanges();

I got the error :

Cannot open database "NewTestDb" requested by the login. The login failed

Once again in my programming career, i am shocked. The same credentials passed in the connection string(in the dbcontext class) works fine if in SSMS/sample sql connection from code-behind but that ain't working here. But when i create NewTestDb manually from SSMS, the connection was successful. Now, when i call the SaveChanges method of CampaignDbContext, i get :

Invalid object name 'dbo.Campaigns'

I have went through tons on SO posts already and don't see anything wrong with my code. Can somebody point out where am i missing/what am i doing wrong?

P.S. I am new to EF.

1 Answers

Thanks to bolkay. I figured it out. Turns out i had to run these specific commands from the Package Manager Console :

enable-migrations
add-migration InitialMigration
update-database

Now, everything's working fine! Cheers!

Related