I have an application that is using Entity Framework 6 (database-first). My database already exists, but I would like to be able to run my application in a new environment and have the code create the database and tables if they do not already exist.
How can this be accomplished in Entity Framework 6? I've seen older examples that use
DbContext.CreateDatabase() but that method is not available in EF6. For what it's worth, the database is in SQL Azure.
EDIT: some folks have been suggesting the CreateDatabaseIfNotExists initialization strategy, which is supposedly the default. Unfortunately, I am getting an error when attempting to run the application in a new environment where the db is not yet created. Perhaps this is because I'm working with Sql Azure? The error is resolved if I create the db and tables manually. Here's the error message:
Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll
Additional information: Cannot open database "MyExampleDatabase" requested by the login. The login failed.
Login failed for user 'ExampleUser'.
Note that the exception appears to be an authentication failure, but this is not the case. I verified that the credentials and connection string are valid. The application works fine and is able to make updates to the db after I create the db & tables manually. But I'd like the application to be able to create the db and tables automatically at runtime if they do not already exist.
Thanks for the feedback. I was able to solve the problem by recreating my ADO.NET entity model using the "Code First from database" option (in Visual Studio 2015). Previously, I used the "EF designer from database" option. Apparently, I needed to opt into "code-first" in order to leverage this feature of EF.
The best way to make sure you get what you want, is to sepperate creation from initialization.
For creation of the database I would use the Azure REST API's or (if you can) the Microsoft.Azure.Management.Sql NuGet package. Creating a database using this API allows you to specify which performance level you want, which determines the price.
For initialization you can use EF like you normally would