How can I create a database and tables at runtime using Entity Framework 6?

asp.net-web-api2 c# entity-framework entity-framework-6 sql-server

Question

I have a programme that makes use of Entity Framework 6. (database-first). I'd want to be able to run my programme in a different environment and have the code generate the database and tables if they don't already exist. My database is already there, but I'd like to be able to run it there.

How is this possible with Entity Framework 6? I've observed earlier instances that make use ofDbContext.CreateDatabase() However, EF6 does not support that way. In case it matters, the database is located in SQL Azure.

EDIT: A few people have suggested the startup approach CreateDatabaseIfNotExists, which is reportedly the default. Unfortunately, when I try to run the programme in a fresh environment where the database hasn't yet been built, I receive an error. Maybe working with SQL Azure has anything to do with this? If I manually build the database and tables, the problem is fixed. The error message is as follows:

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'.

It should be noted that although an authentication failure would seem to be the exception, this is not the case. I checked to make sure the connection string and credentials were legitimate. After I manually build the database and tables, the programme runs well and is able to update the database. However, if the database and tables do not already exist, I would want the programme to be able to generate them automatically during runtime.

1
0
8/9/2016 2:50:07 PM

Accepted Answer

ZZZ_tmp
0
8/9/2016 9:51:00 PM

Popular Answer

Separating creation from initialization is the best approach to ensure that you get what you want.

I would use the Microsoft.Azure.Management.Sql NuGet package or (if you can) the Azure REST APIs to create the database. When building a database using this API, you may choose the performance level you need, which affects the cost.

You may use EF as usual for startup.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow