6. Code first class design tips
• Just design your classes the way you typically would
– (for the most part)
• Use standard conventions
– ID for the ID
• You can still control the database
– Attributes
– Fluent API
8. But what about my database?
• Code First often does the right thing
• But it does need a little guidance
• For example, strings become nvarchar(max)
9. Basic database control
• Data annotations can be used to provide additional context
– System.ComponentModel.DataAnnotations
– https://msdn.microsoft.com/en-
us/library/system.componentmodel.dataannotations(v=vs.110).aspx
• Not specific to Entity Framework
– Used by several other platforms, including MVC
10. Code First conventions
• Tables are automatically pluralized
• Tables are created in the dbo schema
• ID property is created as the primary key
– Identity or auto-count column
17. Creating the Data Context
• Just like creating a normal class
– It's like it's called Code First
public class MusicStoreDbContext : DbContext
{
public DbSet<Artist> Artists { get; set; }
}
19. The Find() method
• Regardless of the data type you're going to need to look the
object up by its key
• Rewriting that code over and over again becomes tedious
• The Find method will do that for you
• Accepts a parameter that maps to the key
• Returns the object if it's found
• Returns null if it isn't
22. Testing requires a known starting state
• Entity Framework provides database initializers to create that
state
• Create a class that inherits from the appropriate option
– CreateDatabaseIfNotExists
– DropCreateDatabaseWhenModelChanges
– DropCreateDatabaseAlways
• Override the Seed method to create database content
• Register the method with Database.SetInitializer