vrijdag 11 januari 2013

Entity framework 5 Migrations, Tips & Tricks




  1. The migrations itself are transactional (so when everything goes wrong, you get another shot).
  2. The migrations reinsert the data after the upgrade.
  3. When adding a required property to an existing entity a not-null column is added to the table. Existing records get a default value.
  4. When making an existing property required make sure all existing records  have a value for the soon to be not null column. If not the upgrade will result in an error.

woensdag 9 januari 2013

Using Entity framework 5’s migrate.exe




Entity framework 5 provides migrate.exe to migrate a database using an external process. When implementing this I encountered several rather unexpected problems which I’ll list up for you, hoping you don’t have to suffer the same frustration.
  1. When you used Nuget to integrate EF5 into your project you’ll find the Register.exe here {Project-root}/packages/EntityFramework.5.0.0/lib/net40/
  2. When using the net40 you’ll need to rename the configuration file to migrate.exe.config (.net 4.5 should make this step unnecessary)
  3. Now you’ll need to call register.exe on the .dll (or .exe) file containing your migrations .cs files. You can either copy the register.exe, config file and EntityFramework.dll to the target directory or you can use the /startUpDirectory parameter. Migrate.exe has a few options:
  • /startupConfigurationFile : I tried this approach first being sure of my configuration file. The attempt failed as EF5 failed to get the connection string resulting in the error below:
ERROR: An error occurred while getting provider information from the database. This can be caused by Entity Framework using an incorrect connection string. Check the inner exceptions for details and ensure that the connection string is correct.
  • /connectionString: So I tried adding the connection string but his resulted in a NullReferenceException.
  • /connectionProviderName: The NullReferenceException you can solve by adding the connectionProviderName
  • /verbose: Writes comments and exception messages to the screen, always usefull
Resulting in a call that looked like this:
Migrate.exe Target.dll /connectionString="Data Source=Server\SQLSERVERNAME; Initial Catalog=DbName; Persist Security Info=True; User ID=sa;Password=xxxx" /connectionProviderName:"System.Data.SqlClient" /verbose

Hope it helps,
Greg