I just wanted to make a couple of further notes about EF Code First that I’ve discovered since I started using it:
- 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:
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
- Creating integer primary key columns that aren’t identities: This one is pretty simple, but when mapping your entities, you must do the following:
- 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.