I just wanted to make a couple of further notes about EF Code First that I’ve discovered since I started using it:

  1. Cascading Deletes: I don’t like cascading deletes – I prefer notification that linked resources must be removed before a resource can be removed. I find it’s too easy to end up deleting things you don’t want to with Cascading deletes on. To disable this behavior by default, you have to update the ModelBuilder’s conventions in your DbContext class like so:
    public partial class MyContext: DbContext
    {
       static MyContext()
       {
           Database.SetInitializer<MyContext>(null);
       }
    
       public MyContext() : base("MyConnectionString")
       {
       }
    
       protected override void OnModelCreating(DbModelBuilder modelBuilder)
       {
           modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
           modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
           //Configurations go here
       }
    }

    Note that after you do this, your next Add-Migration will result in EF attempting to drop and add all of your Foreign Key constraints. Since I migrated my code base to EF code first from model first, my database already had cascading deletes disabled for existing tables. Therefore, I just deleted the Add/Drop Foreign Key code from my migration code

  2. Creating integer primary key columns that aren’t identities: This one is pretty simple, but when mapping your entities, you must do the following:
    this.Property(t => t.Id)
        .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
  3. Unique Indexes – By default, there isn’t a method on PrimitivePropertyConfiguration that allows unique indexes to be created. I found a great solution on StackOverflow that creates an Extension method that will allow you to create unique indexes.