Tip: Getting SQL statements for creating database tables from your Entity Framework model
Posted: (EET/GMT+2)
Situation: you're developing a .NET application with C# and the Entity Framework at the office. You have just decided to add a new table to the database, and have updated your entity model to reflect this change. You go home and decide to continue developing in the evening. But, then you realize you didn't remember to take the latest database backup with you, and your VPN connection server is down for maintenance.
You can't write more code until you get the database to the latest version, and this you cannot do without the backup. You can only get the backup next morning. You have the latest source code, the entity model and Visual Studio at hand, and a local copy of the database, but not with the latest changes. Is your evening coding session an idle one?
What do you think? Luckily, it's not! In Visual Studio's Entity Framework designer, you can both update your model based on the database ("database-first"), or you can work the other way around: model-first.
Since you would only need a single table to be added to your local database copy, this is pretty straightforward: open up Visual Studio and your entity model into the visual designer. Right-click and empty spot, and choose the command "Generate Database from Model". With this command, the main idea is to generate the whole database from scratch.
However, in the above situation (which happened to me) you can only take a portion of the whole script, and run it against your own, local database. In this case, you'd need the CREATE TABLE statement to add that new table.
You can simply copy the part of the script you want to the clipboard, and then fire up SQL Server Management Studio, and run that script into your database. No smoke and mirrors needed, and your table is created! The coding session has been saved!