02 | Beginning Code First Adam Tuliper | Technical Evangelist Christopher Harrison | Content Developer
Code First Simple Code First Creating classes Creating Data Context Initializing the database
Simple Code First
public class Artist { public int ArtistID { get; set; } public string Name { get; set; } public string Bio { get; set; } }
Code first classes… are just classes
Code first class design tips Just design your classes the way you typically would (for the most part) Use best practices ID for the ID You can still control the database Attributes Fluent API
Creating classes
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)
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
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
Table creation TableAttribute Schema Name ColumnAttribute
Strings Nullable nvarchar(max) is the default Attributes StringLengthAttribute MaximumLength MinimumLength RequiredAttribute
Numbers SQL data type is mapped to .NET data type RangeAttribute long becomes BigInt RangeAttribute Maximum Minimum
Numbers and nullability Numbers are value types in .NET .NET property must be marked as nullable Nullable<T> type?
Attributes and database control
Creating the Data Context
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; } }
Creating the DbContext
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
Creating a repository
Initializing the database
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
Initializing the database