Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Code First Doesn't Generate Database

I created a db Context class and added a connection string in my web.config file as instructed in Scott Guthrie's Code First Development with Entity Framework 4. I am running it from a test method. I received several database errors running the tests, but when I finally cleaned up the classes so the test succeeded, I still had no database in the App_data folder.

I added Database.CreateIfNotExists() to the dbContext constructor, but still no sdf file. Anyone know what I am doing wrong?

like image 498
pthalacker Avatar asked Oct 07 '10 00:10

pthalacker


People also ask

What is code first in Entity Framework 6?

6 Entity Framework 6.0 Code first - getting duplicated items in a simple query when filtering by primary key 1 Database not updated using repository pattern and EF Code First Related 853

Can code first create an empty database?

This scenario includes targeting a database that doesn’t exist and Code First will create, or an empty database that Code First will add new tables to. Code First allows you to define your model using C# or VB.Net classes.

How to add code first to a new database?

Code First to a New Database. 1 1. Create the Application. To keep things simple we’re going to build a basic console application that uses Code First to perform data access. 2 2. Create the Model. 3 3. Create a Context. 4 4. Reading & Writing Data. 5 5. Dealing with Model Changes. More items

What is code first development?

Fluent API This video and step-by-step walkthrough provide an introduction to Code First development targeting a new database. This scenario includes targeting a database that doesn’t exist and Code First will create, or an empty database that Code First will add new tables to. Code First allows you to define your model using C# or VB.Net classes.


2 Answers

For the database to be automatically created, the connection string name has to be named exactly as the DbContext subclass name (with namespace).

Eg. Say your DB class is like this:

namespace MyNamespace
{
    public class FooDb : DbContext
    {    
        public DbSet<XXX> ABC{ get; set; }
    }
}

Your connection string should look like so:

  <connectionStrings>
    <add name="MyNamespace.FooDb" connectionString="Data Source=|DataDirectory|MyNamespace.FooDb.sdf" providerName="System.Data.SqlServerCe.4.0"/>
  </connectionStrings>
like image 194
LordHits Avatar answered Oct 06 '22 03:10

LordHits


Check SQL Server Management Studio -> .\sqlexpress

That's where CF has been putting all my databases when I don't specify a connection string.

like image 39
pharophy Avatar answered Oct 06 '22 04:10

pharophy