lintmouse
lintmouse

Reputation: 5119

EF 4.4 Code First - Auto generation creating two instances of database

I recently upgraded from EF 4.3.1 to 4.4 and something odd started happening. I have touched the code since the upgrade, so I can't say with 100% certainty that it was that which caused this issue.

Anyway, when I blow away the existing database and call Update-Database from the PM console, it creates a database, but with the fully-qualified name of my context. I.e., MyProject.Data.MyContext. Previously, it just created a database called MyContext. I can initialize a bunch of data in the database for testing purposes, but when the app runs, it says there is nothing in the database.

When I go look at the database, I see that now there is another database called MyContext (like in the past). When I initialize the test data in that database, the app runs just fine and sees the data.

I am overriding the OnModelCreating method. Basically it looks like this:

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {//My modelBuilder stuff.
base.OnModelCreating(modelBuilder);}

Not much has changed in this method, so I don't think that is the culprit. Has anyone encountered this issue before? Let me know if you want me to post more of my code.

Upvotes: 1

Views: 225

Answers (2)

lintmouse
lintmouse

Reputation: 5119

Okay, so it turns out that I needed to blow away my app.config file since I am using EF Code-First. I started out with a database first approach, but then changed it to Code-First. Once I blew away the app.config file, it worked correctly - only creating one database with the update-database command and using the same database in my code.

Oh, and I was able to set my database name in the context constructor as follows:

MyContext() : base("MyDatabase") { }

Upvotes: 1

Rusty Divine
Rusty Divine

Reputation: 3492

Search your code to make sure there isn't two classes that are implementing DbContext - I've run into this when using scaffolding.

Open your context, and try setting it up with the connection string explicitly, like:

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

Check your web.config to see if anything looks weird with your EF settings and connection strings.

Upvotes: 1

Related Questions