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.
CreateDatabaseIfNotExists
, which is actually the default behaviour. – Charles Mager Aug 9 '16 at 14:16