简体   繁体   中英

Entity Framework migrations changes detection

I've been recently digging into how EF migrations work and I've encountered an issue I could not really understand.

I was reading this article and here's what I saw:

来自msdn的屏幕

At this stage Developer #2 can run Update-Database which will detect the new AddRating migration (which hasn't been applied to Developer 2's database) and apply it. Now the Rating column is added to the Blogs table and the database is in sync with the model.

What I can't get is how EF determines that it has to apply the changes from the AddRatings migration. As far as I know, the workflow is as follows:

  1. Suppose we have two migrations (with the ids 4 and 5) in the project which have not been applied to the db (say, we got the old version of the db with 1, 2 and 3 migrations applied).
  2. Update Db command is run.
  3. EF goes to the db, looks up the MigrationHistory table and gets the latest migration. Then, EF sees that there are migrations 4 and 5 in the project and since the latest migration in the db is 3, it applies 4 and 5.

However, when I look at the screen from the article, I don't really get it. Here's how I would expect it to go:

  1. There are migrations First, AddUrl and AddReaders in the Dev 2 database.
  2. EF looks up the latest migration in the db - it's the AddReaders.
  3. The latest migration in the project is also AddReaders.
  4. Therefore, no changes have to be applied at all.

There's an issue that the code model and the latest migration model are not the same, but EF is able to apply changes to the db anyway, though producing a warning, as the article says.

The question is, what have I got wrong in my reasoning and how EF understands that even though the latest migration in the db and code is the same , there's another migration that has to be applied.

Also, as far as I've understood, the compressed model in the MigrationHistory serves only when the Add-Migration command is run and has nothing to do with the Update-Database command. Is it so?

When performing an update EF compares the set of migrations from the assembly with the set of migrations from the database and applies to the DB all missing migrations. It doesn't matter whether the missing migrations are at the end of history list or somewhere in the middle.

Migrations are compared by MigrationId so you are right, the compressed model has nothing to do with the Update_Database command.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM