0

I have a few questions about creating a database from a model.

Is it possible to do this at runtime? I know you can generate the create sql in the designer but what about during runtime?

Can you create the DDL without creating a connection? Just kind of annoying to add a connect for the sole purpose of creating the DDL.

Is there an automatic way to handle alters? Like if I update the entity/table am I going to have to manually alter the table or is there anything to handle that?

Whats going on in EntityContext.CreateDatabase for sqlce? When I call it I have to recreate the context otherwise I cannot create the tables as they already 'exist'. But they don't really exist as any inserted data is not saved.

Will
  • 10,013
  • 9
  • 45
  • 77

1 Answers1

2

Absolutely. If your database doesn't exist it will create it if you've specified In your constructor:


static EntityContext()
{
//for example to create a db:
Database.SetInitializer(new CreateDatabaseIfNotExists());
}

What do you mean by recreating the context? If you specify Database. in your initialization, SQL CE database will be created. Unfortunately the model becomes the initial source of changes. Future changes need to be made to both the database and the model.

Your SQL CE connect string is as such:

<add name="EntityDemoSite.DataAccess.EntityContext" connectionString="Data Source=|DataDirectory|test.sdf" providerName="System.Data.SqlServerCe.4.0" />

note that the 'name' should match the full namespace of the context class.

Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
Adam Tuliper
  • 29,982
  • 4
  • 53
  • 71
  • Never mind the last question, apparently that only has to deal with linq2sql. SqlCe EF doesn't support calls to CreateDatabase apparently. So is there any way to easily do database/model updates? Like say I add some properties to an existing entity. How would that work with older databases that doesn't have those columns? – Will Oct 28 '11 at 02:31
  • I tried "Database.SetInitializer(new CreateDatabaseIfNotExists());" but I still get "The database file cannot be found" – Will Oct 28 '11 at 02:56
  • I guess for now I will just use SqlCeEngine for creating the database file. – Will Oct 28 '11 at 03:09
  • by default - it will break. EF will query those items, they won't exist and it will fail. As far as I know your best bet is to make the changes to the db, then run the EF Power Tools reverse engineer on it or simply make the change in your code. You can have a check upon app startup to determine if the model is compatible with the db based on a hash by calling: CompatibleWithModel – Adam Tuliper Oct 28 '11 at 06:00
  • a slight bit of info here: http://stackoverflow.com/questions/5656604/updating-database-schema-with-entity-framework-code-first – Adam Tuliper Oct 28 '11 at 06:01