The LibraryReservationSystem database is already existing database. It has no tables. I am expecting EF to create the tables.
That's not correct. If the database exists EF doesn't create any tables in this database. EF can create the database if it doesn't exist. That is the default database initializer CreateDatabaseIfNotExists
that gets applied if you don't change it explicitly. You can select two other initializers: DropCreateDatabaseAlways
or DropCreateDatabaseIfModelChanges
. But neither of those will only create tables in an existing database but instead delete the database completely and create it from scratch including all tables.
What can you do:
DropCreateDatabaseAlways
initializer once to let EF create the database including the tables, then remove the initializer againSeed
method that adds the tables to the database@Slauma's answer is the right one - the tables are created upon initialization. It's probably easiest to just delete the database and let EF create it (if you leave your connection string as is, it will create a database called LibraryReservationSystem on the local machine; you should probably specify an explicit host name if you're going to use the connection string in the config at this point).
You would need something along the lines of:
public class NerdDinnersInitializer : DropCreateDatabaseIfModelChanges<NerdDinners> { }
And you would also need to set the initializer in your Main method:
Database.SetInitializer(new NerdDinnersInitializer());
Word to the wise: NEVER deploy an application with an initializer like the one above. You can see this blog post about how to control initializers via the config file for more details on how to control this in production applications.
I've just ran into the exact same issue - I'd already created my database on a development SQL box inside our network that needs SQL authentication.
When I ran my app, no tables were created. I found this awesome but simple article about creating a Code First Database Initializer Strategy which first checks to see if the database exists and then runs a script against the database to create the tables.
As stated in the article - pay attention that when such a strategy is deployed, whenever the application starts over, all the database tables will be recreated! This strategy should only run once.
But you already knew that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With