共用方式為


EF 4.3 Automatic Migrations Walkthrough

 


The information in this post is out of date.

Visit msdn.com/data/ef for the latest information on current and past releases of EF.

For Automatic Migrations see https://msdn.com/data/jj554735


 

We have released the first go-live release of our Code First Migrations work as part of Entity Framework 4.3.

This post will provide an overview of the functionality that is available inside of Visual Studio for interacting with migrations. We will focus on the workflow that combines automatic and code-based migrations. In this workflow most changes can be automatically calculated and applied. More complex changes can be written out to code-based migrations that can reside in your project.

There is a separate Code-Based Migrations Walkthrough that shows how this same set of changes can be applied using purely code-based migrations.

This post assumes you have a basic understanding of Code First, if you are not familiar with Code First then please complete the Code First Walkthrough.

 

Building an Initial Model & Database

Before we start using migrations we need a project and a Code First model to work with. For this walkthrough we are going to use the canonical Blog and Post model.

  1. Create a new MigrationsAutomaticDemo Console application.
    .

  2. Add the latest version of the EntityFramework NuGet package to the project.

    • Tools –> Library Package Manager –> Package Manager Console.
    • Run the ‘Install-Package EntityFramework’ command.
      .
  3. Add a Model.cs file with the code shown below. This code defines a single Blog class that makes up our domain model and a BlogContext class that is our EF Code First context.

     using System.Data.Entity;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Data.Entity.Infrastructure;
    
    namespace MigrationsAutomaticDemo
    {
        public class BlogContext : DbContext
        {
            public DbSet<Blog> Blogs { get; set; }
        }
    
        public class Blog
        {
            public int BlogId { get; set; }
            public string Name { get; set; }
        }
    }
    
  4. Now that we have a model it’s time to use it to perform data access. Update the Program.cs file with the code shown below.

     using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace MigrationsAutomaticDemo
    {
        class Program
        {
            static void Main(string[] args)
            {
                using (var db = new BlogContext())
                {
                    db.Blogs.Add(new Blog { Name = "Another Blog " });
                    db.SaveChanges();
    
                    foreach (var blog in db.Blogs)
                    {
                        Console.WriteLine(blog.Name);
                    }
                }
            }
        }
    }
    
  5. Run your application and you will see that a MigrationsAutomaticDemo.BlogContext database is created on your local SQLEXPRESS instance.

    MigrationsAutomaticDemoDatabase

 

Enabling Migrations

It’s time to make some more changes to our model.

  1. Let’s introduce a Url property to the Blog class.

     public class Blog
    {
        public int BlogId { get; set; }
        public string Name { get; set; }
        public string Url { get; set; }
    }
    
  2. If you were to run the application again you would get an InvalidOperationException because the database no longer matches your model.

    ”The model backing the 'BlogContext' context has changed since the database was created. Consider using Code First Migrations to update the database ( https://go.microsoft.com/fwlink/?LinkId=238269
    ).” .

  3. As the exception suggests, it’s time to start using Code First Migrations. The first step is to enable migrations for our context. Because we want to use automatic migrations we’re going to specify the –EnableAutomaticMigrations switch.

    • Run the ‘Enable-Migrations -EnableAutomaticMigrations’ command in Package Manager Console.

      .

  4. This command has added a Migrations folder to our project. This new folder contains aConfiguration class. This class allows you to configure how Migrations behaves for your context. For this walkthrough we will just use the default configuration.

    Because there is just a single Code First context in your project, Enable-Migrations has automatically filled in the context type that this configuration applies to.

 

Your First Automatic Migration

Code First Migrations has two commands that you are going to become familiar with.

  • Add-Migration will scaffold the next migration based on changes you have made to your model.
  • Update-Database will apply any pending changes to the database.

We are going to avoid using Add-Migration (unless we really need to) and focus on letting Code First Migrations automatically calculate and apply the changes.

  1. Let’s use Update-Database to get Code First Migrations to push the changes to our model (the new Blog.Url property) to the database.

    • Run the ‘Update-Database’ command in Package Manager Console.

      .

  2. Code First Migrations has now updated the MigrationsAutomaticDemo.BlogContext database to include the Url column in the Blogs table.

     MigrationsAutomaticDemoDatabaseUpdated

 

Our Second Automatic Migration

Let’s make another change and let Code First Migrations automatically push the changes to the database for us.

  1. Let’s introduce a new Post class.

     public class Blog
    {
        public int BlogId { get; set; }
        public string Name { get; set; }    
        public string Url { get; set; } 
    
        public List<Post> Posts { get; set; }
    }
    
    public class Post
    {
        public int PostId { get; set; }
        [MaxLength(200)]
        public string Title { get; set; }
        public string Content { get; set; }
    
        public int BlogId { get; set; }
        public Blog Blog { get; set; }
    } 
    
  2. Now use Update-Database to bring the database up-to-date. This time let’s specify the –Verbose flag so that you can see the SQL that Code First Migrations is running.

    • Run the ‘Update-Database –Verbose’ command in Package Manager Console.

.

Adding a Code Based Migration

Now let’s look at something we might want to use a code-based migration for.

  1. Let’s add a Blog.Rating property.

     public class Blog
    {
        public int BlogId { get; set; }
        public string Name { get; set; }
        public string Url { get; set; } 
        public int Rating { get; set; }
    
        public List<Post> Posts { get; set; }
    }
    
  2. We could just run Update-Database to push these changes to the database. However, were adding a non-nullable Blogs.Rating column, if there is any existing data in the table it will get assigned the CLR default of the data type for new column (Rating is integer, so that would be 0). But we want to specify a default value of 3 so that existing rows in the Blogs table will start with a decent rating.

    Let’s use the Add-Migration command to write this change out to a code-based migration so that we can edit it. The Add-Migration command allows us to give these migrations a name, let’s just call ours AddBlogRating.

    • Run the ‘Add-Migration AddBlogRating’ command in Package Manager Console.

      .

  3. In the Migrations folder we now have a new AddBlogRating migration. The migration filename is pre-fixed with a timestamp to help with ordering. Let’s edit the generated code to specify a default value of 3 for Blog.Rating.

    The migration also has a code-behind file that captures some metadata. This metadata will allow Code First Migrations to replicate the automatic migrations we performed before this code-based migration. This is important if another developer wants to run our migrations or when it’s time to deploy our application.

     namespace MigrationsAutomaticDemo.Migrations
    {
        using System.Data.Entity.Migrations;
    
        public partial class AddBlogRating : DbMigration
        {
            public override void Up()
            {
                AddColumn("Blogs", "Rating", c => c.Int(nullable: false, defaultValue: 3));
            }
    
            public override void Down()
            {
                DropColumn("Blogs", "Rating");
            }
        }
    }
    
  4. Our edited migration is looking pretty good, so let’s use Update-Database to bring the database up-to-date.

    • Run the ‘Update-Database’ command in Package Manager Console.

 

Back to Automatic Migrations

We are now free to switch back to automatic migrations for our simpler changes. Code First Migrations will take care of performing the automatic and code-based migrations in the correct order based on the metadata it is storing in the code-behind file for each code-based migration.

  1. Let’s add a Post.Abstract property to our model.

     public class Post
    {
        public int PostId { get; set; }
        [MaxLength(200)]
        public string Title { get; set; }
        public string Content { get; set; }
        public string Abstract { get; set; }     
    
        public int BlogId { get; set; }
        public Blog Blog { get; set; }
    }
    
  2. Let’s use Update-Database to get Code First Migrations to push this change to the database using an automatic migration.

    • Run the ‘Update-Database’ command in Package Manager Console.

 

Data Motion / Custom SQL

So far we have just looked at migration operations that can leave all the data in place, now let’s look at something that needs to move some data around. There is no native support for data motion yet, but we can run some arbitrary SQL commands at any point in our script.

We just added the Abstract column. Let’s pre-populate it for existing posts using text from the Content column.

  1. Use the Add-Migration command to let Code First Migrations add an empty migration for us. We’re going to call this migration PopulatePostAbstract.

    (The migration will be empty because there are no pending model changes that haven’t been applied to the database)

    • Run the ‘Add-Migration PopulatePostAbstract’ command in Package Manager Console.
  2. Update the migration to run some custom SQL that will populate the Abstract column.

     namespace MigrationsAutomaticDemo.Migrations
    {
        using System.Data.Entity.Migrations;
    
        public partial class PopulatePostAbstract : DbMigration
        {
            public override void Up()
            {
                Sql("UPDATE dbo.Posts SET Abstract = LEFT(Content, 100) WHERE Abstract IS NULL");
            }
    
            public override void Down()
            {
            }
        }
    }
    
  3. Our edited migration looks good, so let’s use Update-Database to bring the database up-to-date. We’ll specify the –Verbose flag so that we can see the SQL being run against the database.

    - Run the ‘Update-Database –Verbose’ command in Package Manager Console.
    

 

Migrate to a Specific Version (Including Downgrade)

So far we have always upgraded to the latest migration, but there may be times when you want upgrade/downgrade to a specific migration.

  1. Let’s say we want to migrate our database to the state it was in after running our AddBlogRating migration. We can use the –TargetMigration switch to downgrade to this migration. This is going to cause some columns that were added as part of an automatic migration to be dropped automatically on the way down. Code First Migrations won’t let this happen without you knowing about it, so we need to specify the –Force switch to acknowledge that we are OK with the potential data loss.

    • Run the ‘Update-Database –TargetMigration:"AddBlogRating" –Force’ command in Package Manager Console.

      .

  2. This command will run the Down script for our PopulatePostAbstract migration, then use the automatic pipeline to revert the addition of the Abstract column.

If you want to roll all the way back to an empty database then you can use the Update-Database –TargetMigration:$InitialDatabase –Force command.

 

Getting a SQL Script

If another developer wants these changes on their machine they can just sync once we check our changes into source control. Once they have our new migrations they can just run the Update-Database command to have the changes applied locally. However if we want to push these changes out to a test server, and eventually production, we probably want a SQL script we can hand off to our DBA.

  1. Let’s run the Update-Database command but this time we’ll specify the –Script flag so that changes are written to a script rather than applied. We want a script to go from an empty database ($InitialDatabase) to the latest version.

    Note: You can also specify a target migration to generate a script to the database state at the end of a code-based migration. If you don’t specify a target migration, Migrations will use the latest version as the target (including any automatic migrations that have been applied since the last code-based migration).

    • Run the ‘Update-Database -Script -SourceMigration:$InitialDatabase’ command in Package Manager Console.

      .

  2. Code First Migrations will run the migration pipeline but instead of actually applying the changes it will write them out to a .sql file for you. Once the script is generated, it is opened for you in Visual Studio, ready for you to view or save.

 

Summary

In this walkthrough you saw how to use automatic migrations to push model changes to the database. You saw how to scaffold and run code-based migrations when you need more control. You also saw how to upgrade and downgrade your database. Finally we looked at how to get a SQL script to apply migrations to a database.

Rowan Miller

Program Manager

ADO.NET Entity Framework

Comments

  • Anonymous
    February 10, 2012
    What if I develop both the Code-First model and database schema by hand (using Microsoft SQL Server Data Tools for Visual Studio which is more suited for database development and versioning then relying on EF Migrations).. Is there a way to compare Code-First model against existing database and find out all the differences? Here is the concept: github.com/.../data

  • Anonymous
    February 10, 2012
    @Konstantin Tarkus – I’d like to understand your scenario better. If you are building the database by hand (not letting Code First generate it) it seems it would be better to have a Code First model created for you from the existing database, rather than having to hand code the database and the also hand code the Code First model. We have a ‘Reverse Engineer Code First from Database’ tool available in the EF Power Tools, which you can point at a database and it will create the Code First model for you. It would also be great if you provide more information on “more suited for database development and versioning”. Are there scenarios you would like to see supported in Code First Migrations? Or are you also including objects in your database that aren’t relevant to the Code First model (SPORCs etc.)?

  • Anonymous
    February 10, 2012
    @Rowan Miller - The problem is I don't like neither entities model nor database schema to be generated by automation tools, because every automation tool have its limits and going beyond this limits sometimes not worth the efforts. I want both database schema and entities model (the code) be hand crafted. During that kind of development db schema and the POCO model may become out of sync eventually (for example you added one type of foreign key in the database but another type of relationship between POCO classes in the model). The tool I miss in EF tool set is a Schema-2-Model comparison. Which I could run from time to time (or each time at db initialization stage), making sure db schema and code-first entities model are compatible. Again I don't want neither entities be generated from the database nor database schema based on the model. I just want to be able to compare my existing database schema with my existing POCO entities model. I'm pretty sure that kind of comparison tool can be easily implemented and is going to take much less efforts then creation of the EF Migrations or EF Power Tools.

  • Anonymous
    February 10, 2012
    @Konstantin Tarkus – That makes sense. You probably wouldn’t want to use Migrations for this, you can use ((IObjectContextAdapter)myContext).ObjectContext.CreateDatabaseScript() to get a SQL script for the database the Code First model is expecting. Then just use an existing schema compare tool to see the differences with your current database. It’s not something our team is planning to work on in the near future… unless we saw a strong customer demand for it.

  • Anonymous
    February 10, 2012
    Of cause the database have more objects than the Code First model; the model just just won't be able to describe everything SQL server has (indexes, statistics, columns order, object descriptions, computed columns, sprocs, views etc) anytime soon regardless of how many efforts are putted into EF Migrations and Code First metadata infrastructure. That's why I strongly believe that the database should be developed with database tools and not EF Migrations. Microsoft SQL Server Data Tools does this job extremely well with it's version control functionality, snapshots, localdb etc. EF Migrations won't ever be able to become close. On the other hand generated POCO classes from the database is not an option, because they differ from what ideally should be there. POCO classes don't fully reflect the db schema.. db schema is made keeping optimization stuff in mind and POCO classes are solely business objects, reflecting a core for application's business logic.

  • Anonymous
    February 10, 2012
    I agree with Konstantin Tarkus, the database should be built by hand, and the DbMigration may be wrong way.

  • Anonymous
    February 11, 2012
    Congratulations guys! Migrations make the development process with code-first approach even better! Keep the good work!

  • Anonymous
    February 11, 2012
    In EF 4.2, I could manually synch the model with database so that if I had added a column in the db I could then simply add that column to the model and recompile. Very simple and efficient. That no longer seems to work in EF 4.3. If the code model (poco) gets out of synch with the db, it just throws errors. Changes now need to be synced using the "Update-Database" command and that sometimes does not work even when the code model is the same as the db. Steps to reproduce

  1. Build the above project to the end of the 'Your First Automatic Migration' section
  2. Add a column in the database such as content varchar(100)
  3. Run the console app. No errors but extra db column is ignored.
  4. Add the same 'content' column to the model
  5. Run the console app. Throws the 'The model backing the 'BlogContext' context has changed since the database was created. Consider using Code First Migrations to update the database,"  (Should just work as it did in 4.2)
  6. Run the Package Manager Console 'Update-Database' with expectation that this would re-sync the two, instead get error 'Column names in each table must be unique. Column name 'Content' in table 'Blogs' is specified more than once.'
  7. Removed 'Content' column in db and re-ran the 'Update-Database'. This re-synced the code model to the db table. That's good, but is it now necessary to run the 'Update-Database' command even when the code model and the db are equivalent? How does EF4.3 track the differences now? Is it possible to use the EF4.2 way of working without having to invoke 'Update-Database'  for every change?
  • Anonymous
    February 11, 2012
    @WillC: The behavior here has not changed between 4.2 and 4.3 (unless there is a bug, in which case we'll fix it.) In 4.2 you will get an exception at step 5 unless you either told EFnot to create the EdmMetadata table or manually deleted the table from your database after it was created. If you want to work the same way in 4.3 then just delete the MigrationHistory table. EF will then assume that the database is up-to-date just as it did in 4.2. On SQL Server the MigrationHistory table is marked as a system table so you may need to look under System Tables in your database to find it. Thanks, Arthur

  • Anonymous
    February 12, 2012
    I see you have added MigrateDatabaseToLatestVersion<TContext, TMigrationsConfiguration> database initializer strategy (msdn.microsoft.com/.../hh829293(v=vs.103).aspx). You should definitely promote the ‘Database.SetInitializer(new MigrateDatabaseToLatestVersion< TContext, TMigrationsConfiguration >());’ type of code-invoked migration, in your blog post. Especially for EF w/ SQL CE, this initializer is a superb feature for enabling client-side database migrations.

  • Anonymous
    February 12, 2012
    How would one go about listing all the automatic migrations that have been made, and in fact how would one get any idea what has changed between migrations when using the automatic migrating? Where are they stored, and how are they viewed? Btw, Awesome work on this one! Thanks, Lari

  • Anonymous
    February 12, 2012
    @Lari, You can use the Get-Migrations command to list the migrations that have been applied to the target database. It is not very easy to figure out what is contained in a particular auto-migration. One thing to try would be to use -Script to script out the SQL for a specific auto-migration by using the -SourceMigration/-TargetMigration parameters. Auto-migrations are not actually stored directly. What we do is store model snapshots in the code-behind of the code-based migrations. We then use these to compute auto-migrations on the fly. Cheers, Andrew.

  • Anonymous
    February 12, 2012
    I may have missing something here but is there a way to automatically migrate changes to a production site which doesn't need the use of a SQL script generated by the ' Update-Database -script' PM command? As a an example we're developing a database structure which is rolled out to a number of web sites as core part of a CMS. During on ongoing development we're make changes to the entity models which need to be propagated to the live sites during updates. From what I read here I can only do this by running the SQL scripts against each of the databases (SQL Server Compact 4) or by downloading each database in turn and issuing 'Update-Database'. Incidentally, I'm using Database.SetInitializer(Of <context>t)(New SiteInitialiser()) in Application_Start.

  • Anonymous
    February 13, 2012
    @Huihui Jin & @Konstantin Tarkus – That’s fine, migrations gives a lot of folks the solution they want but we realize Code First Migrations won’t be for everyone. Mapping Code First to a hand built database is still a core scenario as we move forwards with Code First. @Vegplot – There is a MigrateDatabaseToLatestVersion database initializer that will update whichever database your context is pointing to. Presumably, when you deploy to production your context will be updated to target your production database. Setting the MigrateDatabaseToLatestVersion initializer will then take care of updating the production database. There are also other options for triggering the migrations process from code - romiller.com/.../running-scripting-migrations-from-code. The Update-Database command also has ConnectionString and ConnectionProviderName parameters that can be used to target a different database.

  • Anonymous
    February 14, 2012
    Everything works fine when I try migrations from console app or unit test project - but I am getting weird messages if I try to enable a class library. Are there any limitations or caveats? Some of the errors point to my web project so I suspect some dependency on the "root" project. I also see app.config added - which is unusual for class library. What is the right pattern in the normal case when I have my MVC web app, business layer, data access (in separate projects)? Which to instrument and where to keep Migrations folder? I assumed it's data access class library project...is that right?

  • Anonymous
    February 15, 2012
    @ivo – Keeping migrations in the data access class library is probably the cleanest approach. You will need to use the –StartupProject parameter on the migrations commands to let migrations know to use the config file etc. from your MVC project.

  • Anonymous
    February 15, 2012
    Rowan - sorry - I can't make this work. It's still black magic to me. I have Migrations folder in my data access project. When I try Add-Migration -StartupProjectName  ...DataAccess  AddFoo I am getting System.IO.FileNotFoundException: Could not load file or assembly '....WebUI' or one of its dependencies I have EF and conn.string in my web.config - but why it complains about mvc project??? What exactly configuration is needed in this case? connection string? I am doing trial and error. Is there any documentation beyond powershell help? I hope Julie L will help...but I am stuck now. I can't even figure out how to disable migrations and go back to the old model... get-help -examples is not really helping

  • Anonymous
    February 16, 2012
    @ivo - Your command should be something like 'Add-Migration AddFoo -StartupProject <my MVC project name>'. If this isn't working, any chance you can send us a solution that reproduces the issue so we can take a look? Use the 'email blog author' link at the top right of this page, we'll reply so you have an address to email the solution to.

  • Anonymous
    February 16, 2012
    I've updated an existing MVC3 Website Solution from EF4.1 to the new EF4.3 bits so I can take advantage of the new Migrations features. I install the necessary bits via the Package Manager and am able to successfully enable the Migrations feature with Enable-Migrations -EnableAutomaticMigrations which creates the expected Migrations folder and Configuration.cs, however when I change my model and try to call Update-Database I get the following error: Name: Update-Database System.NullReferenceException: Object reference not set to an instance of an object.   at System.Data.Entity.Migrations.Extensions.ProjectExtensions.GetFileName(Project project, String projectItemName)   at System.Data.Entity.Migrations.MigrationsCommands..ctor(Object project, Object startUpProject, String configurationTypeName, String connectionStringName, String connectionString, String connectionProviderName, PSCmdlet cmdlet) Object reference not set to an instance of an object. I can't see any major difference between my existing project and the project created via the above walkthrough (which works fine) - has anyone else seen this or can shed any light on what may be wrong?

  • Anonymous
    February 16, 2012
    I've just fixed my own issue reported above - 17 Feb 2012 7:46 AM and though I'd give an update for anyone else who has the same issue - I simply needed to ensure that my MVC3 project was set as the Startup Project in the solution! My MVC3 website is Azure hosted and so I had my Azure project as my default Startup Project to aid in debugging at runtime - switching it over resolved my Update-Database woes

  • Anonymous
    February 20, 2012
    I am having trouble with MigrateDatabaseToLatestVersion and Sql Server Compact. I create a new instance of my subclass of MigrateDatabaseToLatestVersion (instantiated with my connection string that specifies the SDF file and the SQL CE 4.0 provider). I call Database.SetInitializer with the instance of my migration initializer. The first time I create a DbContext, everything seems to be fine. If the SDF file exists, it is opened and migrated if necessary. if the database doesn't exist, it is created at the current version. The problems crop up when I try to instantiate a new DbContext after one has already been opened. I dispose of the current DbContext (and null it out). I then update my connection string to reflect the new SDF file and call Database.SetInitializer with yet another instance of my subclassed MigrateDatabaseToLatestVersion (to reflect the new connection string). If the database does not exist, it is not created. If the database exists, it opens, but it is not migrated which causes exceptions when I try to modify data. Any guidance on using Migrations with SQLCE would be very much appreciated.

  • Anonymous
    March 01, 2012
    @Gaz – There is also a –StartupProject parameter you can use to tell migrations which project to treat as the startup project @Craig Jacobs – Database initialization is a “once per AppDomain” task by default. You can use myContext.Database.Initialize(force: true) to force it to run again. However, in your scenario, it seems like using DbMigrator directly might be easier;  romiller.com/.../running-scripting-migrations-from-code

  • Anonymous
    March 04, 2012
    I would like to know how will the migrations be handled in the following scenario (if the scenario is possible at all): You have a compiled dll of classes and contexts that are imported in a project and extended. For example, classes are declared as partial, as well as the db context, and they are compiled and refferenced by a new project. A database is initialized without problem, and then you decide to add a child table, so you extend the dbcontext to add the table/class and also extend the parent class to add a reference. What is the suggested route for this to happen? Have you tested or support this scenario? Thanks in advance for any insight

  • Anonymous
    March 05, 2012
    @Mihalis - The idea of having a base model in one assembly and extending it in another is absolutely supported. Partial classes won't work in this scenario, since they are just compiler sugar and all parts of the partial class must be in the same project. You can derive from the base classes though, we've seen people do this successfully. If you hit any problems with the implementation then start up a Stack Overflow thread and we'll help you out.

  • Anonymous
    March 05, 2012
    Rowan, thanks for the reply. I have opened a question before I posted here: stackoverflow.com/.../ef-code-first-modular-design I will specify the scenario more there

  • Anonymous
    March 07, 2012
    In Automatic migration , if we rename column then use "update database" it gives error as "Automatic migration was not applied because it would result in data loss." In Add migration (can say manual migration) it directly adds or updates column but losses existing data. Is their any way to prevent data loss when we rename column?? Please help.

  • Anonymous
    March 08, 2012
    @sandysrs - You need to Add-Migration and then edit the scaffolded code to make it a rename rather than an add and a drop.

  • Anonymous
    March 12, 2012
    Thank @Rown M. It works for me.. also done some research and found that dbmigration methods like Rename, delete methods can be used to manipulate database.

  • Anonymous
    April 03, 2012
    It looks to me like no matter where in the code I place the latest added property, in the database it will be mapped to the last column. Is there a way to change this behavior?

  • Anonymous
    April 04, 2012
    @wrupper - Not using an automatic migration. You would need to use Add-Migration to give you a code based migration. Then replace the simple AddColumn call with a custom Sql call to insert the column in the correct place.

  • Anonymous
    April 10, 2012
    I recently started using automatic migration.  I am adding data using the Configuration Seed method.  When I issue the Update-Database -Verbose command, the Package Manager Console is reporting the following error "Validation failed for one or more entities. See 'EntityValidationErrors' property for more details." after initiating the Seed method.  Is there any way to debug the Seed method?  Setting break points in the code does not work when calling commands from the Package Manager Console.

  • Anonymous
    April 10, 2012
    @karen3000: the easiest way to diagnose what is going on would be to write a simple program that instantiates the MigrationConfiguration and then passes an instance of your DbContext to the Seed method. You can the use GetValidationErrors on the context to find out exactly what validation rules were triggered. In any case, it seems to me that it would be nice if we provided an even simpler way to do this. I will add an item to our backlog for this.

  • Anonymous
    May 04, 2012
    Whole migration thing has got issue with MySQL. www.cnblogs.com/.../2388177.html Translated Below translate.google.co.in/translate)%253BALTER%2BTABLE%2B%2560Migration%2527%2Bat%2Bline%2B5%26hl%3Den%26prmd%3Dimvns Something similar happened to me in latest version i.e. 5 Beta 2

  • Anonymous
    May 07, 2012
    @IsmailS - Thank you for reporting this, we've opened a bug and are looking into it now.

  • Anonymous
    May 11, 2012
    @Rowan thanks for considering the issue. I found today on stackoverflow.com/.../148271 that some digging on this issue has already been done here brice-lambson.blogspot.in/.../using-entity-framework-code-first-with.html. Just thought it will be useful to you.

  • Anonymous
    May 14, 2012
    @IsmailS - Brice is on the EF team too, you probably noticed that he opened a couple of bugs against the MySQL provider to get the issues fixed.

  • Anonymous
    May 30, 2012
    My package manager console just crashed VS 2010 whenever I try to use it, so this is not helpful. Is there some other way to enable migrations? Windows 7 X64 VS 2010 SP1

  • Anonymous
    May 30, 2012
    @Mike Nacey - There are APIs you can use but that's not going to be a great option for you. I'm running the same setup - Windows 7 X64 VS 2010 SP1 without issue... of course there are a lot of other variables at play too :) Do you have the latest version of NuGet? I'm wondering if upgrading might get rid of the issue for you. If you have the latest version of NuGet and VS is consistently crashing for multiple solutions, then use the 'Email Blog Author' link at the top right of the page to make contact with us and we'll try and work out what is happening.

  • Anonymous
    June 24, 2012
    We have problems with our build server (tfs) in connection with the ef migrations. with our local builded release dlls, all is ok. but if we build the same code on build server and then run the unit tests, ef migrations have an error with "AutomaticMigrationsDisabledException: Unable to update database to match the current model because there are pending changes and automatic migration is disabled". have you any idea?

  • Anonymous
    June 25, 2012
    @Ricardo GER - This suggests that the model in the dll doesn't match the model that was used to generate the last migration (i.e. there have been changes to the model after the last migration was generated). Could this be the case?

  • Anonymous
    June 25, 2012
    Hi Rowan, thx for your response. both assemblies are logical completely the same (i used tools such NDepend, BitDiffer & Framework Design Studio) = both are based on the same source code. if i take a look at a bit comparison (with WinMerge) the assemblies have some different bits (I have no idea why). but I would expect only logical changes lead to problems for ef migrations? i can send you a repro... ricardo.wickel at bewotec de

  • Anonymous
    June 27, 2012
    @Ricardo GER - I've emailed you to get the repro.

  • Anonymous
    May 11, 2015
    Thank you very much for the step-by-step details. I have a query on the migration. Is there any way to mix automatic and coded migration? I have a scenario where there is a change to the precision of a decimal column which is part of non-clustered index. Now this need the indx to be dropped and recreated. However I don't want to use the coded approach to do the migration. Is there any way to drop the index before the auto-migration and then to recreate (may be in Seed method) the index after the migration?