Filed under C# , code first , entity framework , migrations
I've been using Entity Framework migrations for a few weeks now and I'm having a great time with. However, I've notice that every now and then Entity Framework throws an error when I try to run the 'Update-Database' command.
Whenever you get a message 'Could not load file or assembly or one of its dependencies. The system cannot find the file specified.' there are a few steps that I've noticed you can do to help work around this type of error.
- Step 1: Firstly, ensure that your models and any relationships that you've setup are correct. Sometimes this error means that you have incorrectly setup a join or a relationship previously setup is broken. At present the error messaging returned by migrations is a tad lacking and it returns the above error for broken model relationships.
- Step 2: If you change your models I find that unless I edit my Data Context file I get this error. My solutions usually contain many projects. I don't know if that is the reason I get this error message but if I update one of my models without altering the context file migrations continues to return the above message for me. If I don't need to alter the context file (usually I don't as I've just added a new column) then simply pressing space and re-saving the context file does the trick.
- Step 3: Check your database isn't 'blocking' migrations from running. I ran into a few occurances where I would have manually deleted my database and occasionally this would stop migrations from creating a new database. This is a simple fix. Just right click on the Databases heading in SQL Server and click on 'refresh'. If a refresh doesn't solve the issue, try closing SQL Server Management Studio down and restarting it again.
- Step 4: Clean your build history and try a rebuild before running 'Update-Database'.
- Step 5: Lastly, try forcing code first to run by using '- Force'. For example 'Update-Database -Force'. This command is also useful for telling migrations to carry out a task that would result in a data loss.
If you continue to get the error message mentioned above then the issue is nearly always down to your code. Recheck it and try again. I'm sure as Entity Framework Migrations matures they will be able to return better, more meaningful, error messages.