Entity Framework Code-First Migrations

By Chris Scott

Presentation code on github

Created using reveal.js

Creating the Project

  1. Create MVC project with Web API template
  2. Create context class that inherits from DbContext
    
    									public class ServicesContext : DbContext
    								

Enabling Code-First Migrations

  1. Enable migrations from the Package-Manager console
    
    									PM> Enable-Migrations
    								
  2. Allow Code-First migrations in the generated Configuration.cs
    
    									public Configuration() 
    {
        AutomaticMigrationsEnabled = true;
    }
    								

Build Models

  1. Create basic C# objects
  2. Any references to other objects should simply be that type, NOT an int ID type.
    Good:
    
    									public Contact ServiceAgentContact { get; set; }
    								
    Bad:
    
    									public int ServiceAgentContactId { get; set; }
    								

Migrating

  1. Add entities to DbContext to be picked up on migration
    
    									public DbSet<Contact> Contacts { get; set; }
    								
  2. Update from Package-Manager console
    
    									PM> Update-Database
    								

Basics Notes and Gotchas

  • References to other models default to many-to-one, and optional
  • Primitives default to non-nullable, as well. Use Nullable version to fix
    
    ...									
    public int? OptionalValue { get; set; }
    public DateTime? OptionalDate { get; set; }
    ...
    								

Configuring

Use Attributes to enhance relationships


...
//Make Partner required for this model.
[Required]
public Partner Partner { get; set; }
public string CompanyName { get; set; }
...
							

Advanced

Modify relationships during migration run using Fluent API


public class ServicesContext : DbContext
{
	protected override void OnModelCreating(DbModelBuilder modelBuilder)
	{
	    modelBuilder.Entity<Partner>()
	        .HasOptional(p => p.Logo)
	        .WithOptionalDependent()
	        .Map(k => k.MapKey("Logo_Id"));
	    ...
	}
}
						

Will set Partner.Logo to be 1:1, but still optional

Questions?