3

I have created a windows form application:

  1. A presentation library with several windows forms
  2. A class library with a data layer
  3. A class library to access a database

I'm using EntityFramework 4.1 with Code First Approach and SQL Compact 4.0 database.

I created a connection string in the app.config file in the class library project used to connect to the database. The problem is that the connection string has apparently no influence on the database creation. I mean that everything is working fine with the program but even if I specify a location for the database this does not have any effect!

Am I writing in the right app.config? Do I need to initialize my DbContext class in a specific way? (today I do not pass any connection string in the constructor)

DbContext class:

public class MyDB : DbContext
{
    public DbSet<ContactPerson> ContactPersons { get; set; }

    public DbSet<Customer> Customers { get; set; }

    public DbSet<Project> Projects { get; set; }

    public DbSet<Quotation> Quotations { get; set; }

    public MyDB()
    : base("MyDatabase")
    {

    }
}

App.config connection string:

<add name="MyDatabase" connectionString="Data Source=MyDB.sdf" 
providerName="System.Data.SqlServerCE.4.0">
Ms. Nobody
  • 1,219
  • 3
  • 14
  • 34
Francesco
  • 964
  • 2
  • 17
  • 41
  • I just noticed that the application is creating the database in SQL server express instead of in a file. Why is this happening? – Francesco Jul 15 '11 at 12:17

3 Answers3

6

You need to put the app.config in the application (.exe) project. The app.config file should look like in this blog post (case sensitive): http://erikej.blogspot.com/2011/04/saving-images-to-sql-server-compact.html and the names should be MyDB, not MyDatabase...

ErikEJ
  • 40,951
  • 5
  • 75
  • 115
0

Have you tried seeding the DB? You have to inject some data so EF creates the DB, if you don't the model definition is just like a statement of intention.

public class ContextInitializer : DropCreateDatabaseIfModelChanges<DBContext>
{
    protected override void Seed(DBContext context)    
    {
        context.Add(new Customers()); //add a Customer, for example
    }
}

Then look in your Debug/Release folder and check if the DB is created properly.

There is an article by Microsoft explaining all this process in more detail, they have a neew tutorial that replaces the "Magic Unicorn" tutorial, see http://msdn.microsoft.com/en-US/data/jj193542

Baz
  • 36,440
  • 11
  • 68
  • 94
Hannish
  • 1,482
  • 1
  • 21
  • 33
0

Your connection string is wrong, it should be this:

add name="MyDB" connectionString="Data Source=MyDB.sdf" providerName="System.Data.SqlServerCE.4.0"

Note that the Name must match the name of your context class for it to auto detect the connection.

Solmead
  • 4,158
  • 2
  • 26
  • 30