Code first is useful in Domain Driven Design.
Code first use Convention based migration- it is a set of rules to automatically configure a conceptual model based on domain class definition.
Type Discovery- Code first approach generates classes for the properties set in DBSet and also includes referenced types that are included in classes, even if referenced types are defined in another assembly.
The conventions for the type discovery are:
- Code-First includes types defined as a DbSet property in context class.
- Code-First includes reference types included in entity types even if they are defined in different assembly.
- Code-First includes derived classes even if only the base class is defined as DbSet property.
Assuming entities are created and DBContext is set along with the DB Connection string to enable migration use -
enable-migration command in package manager console.
once the migrations are enabled Migrations folder is created with the InitalCreate.cs class. Any further changes to the model a version of changes are created with a Up() and down() method which helps to Migrate and Rollback the model changes to database.
To update the last changes to the DB use add-migration "migration title" and update-database command in console.
This should now update or create Initial tables and changed schema. Along side this a Seed() method is called. You may need to add the initial/sample data to tables use the context for same in Seed() method.
To Rollback the changes use update-database -targetmigration "migration title". I find this a bit confusing initially but what this command does is it takes back the database state to the last best migration performed rollingback the latest changes performed.
While doing so you may receive error-
Unable to generate an explicit migration because the following explicit migrations are pending: [201704251318501_migrationname]. Apply the pending explicit migrations before attempting to generate a new explicit migration.
This seems to complaining about the migration which are performed where a version is missing. So migrations has to be happen in a sequence of it was created.
Hope this helps.