3

I'm a bit confused about Entity framework, I would like to use code-first approach; infact I would like to write how my database tables are composed through class definition.

The main problem is that I need to create a database (or open it) by choosing dinamically it's path (the user can choose what database to open and can create new one when he wants). I've chosen Sql server compact to achieve this, however I still don't understand how to use code-first approach for this situation because I don't understand how to choose where database should be created with code-first approach, if is possible.

Can anyone explain what I'm doing wrong and suggest a different route, if any? Thanks

Francesco Belladonna
  • 11,361
  • 12
  • 77
  • 147

1 Answers1

8

I just had the same problem a few days ago. Here's how I got it to work:

In your application startup code add the following:

using System.Data.Entity.Database;

// ...

DbDatabase.SetInitializer(new MyDbInitializer());
DbDatabase.DefaultConnectionFactory = new SqlCeConnectionFactory(
    "System.Data.SqlServerCe.4.0", 
    @"C:\Path\To\", 
    @"Data Source=C:\Path\To\DbFile.sdf");

The Initializer should look something like this:

using System.Data.Entity.Database;

public class MyDbInitializer : CreateDatabaseIfNotExists<MyDbContext>
{
    protected override void Seed(MyDbContext context)
    {
        // create some sample data
    }
}

If the CreateDatabaseIfNotExists is not the thing you want, there are more kinds of initializers you can use, or you can also create your own. More information on that can be found here:

http://blog.oneunicorn.com/2011/03/31/configuring-database-initializers-in-a-config-file/

Hope this helps.

LueTm
  • 2,366
  • 21
  • 31
  • I'm testing, however I have to wait for visual studio sp1 installation; I think it's a part of the problem (I'm really digging **a lot** through the web, it looks like I'm missing a lot of things due to SP1 missing) – Francesco Belladonna Sep 18 '11 at 01:21
  • With what you suggest, the code work, but it doesn't generate any database on path specified by SqlCeConnectionFactory, and unfortunately that's what I need, I must specify the path while using code first...Argh – Francesco Belladonna Sep 18 '11 at 03:59
  • 1
    DropCreateDatabaseAlways try this one! (it does for me like this) – LueTm Sep 18 '11 at 10:20
  • I'm using that, it doesn't change anything. However I noticed I have a problem: the ADO .NET Entity Model Template (the one when you click add item on project), is missing SQL Server Compact 4.0 provider (while server explorer have it), I definitely have problems with this and I don't know how to fix it :\ – Francesco Belladonna Sep 18 '11 at 12:32
  • 1
    It works!!! I was missing Data Source in the last string passed to the constructor... Woah I'm happy now!! – Francesco Belladonna Sep 18 '11 at 13:01