Download presentation
Presentation is loading. Please wait.
Published byMorgan Lang Modified over 5 years ago
1
02 | Beginning Code First Adam Tuliper | Technical Evangelist
Christopher Harrison | Content Developer
2
Code First Simple Code First Creating classes Creating Data Context
Initializing the database
3
Simple Code First
4
public class Artist { public int ArtistID { get; set; } public string Name { get; set; } public string Bio { get; set; } }
5
Code first classes… are just classes
6
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
7
Creating classes
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 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
11
Table creation TableAttribute Schema Name ColumnAttribute
12
Strings Nullable nvarchar(max) is the default Attributes
StringLengthAttribute MaximumLength MinimumLength RequiredAttribute
13
Numbers SQL data type is mapped to .NET data type RangeAttribute
long becomes BigInt RangeAttribute Maximum Minimum
14
Numbers and nullability
Numbers are value types in .NET .NET property must be marked as nullable Nullable<T> type?
15
Attributes and database control
16
Creating the Data Context
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; } }
18
Creating the DbContext
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
20
Creating a repository
21
Initializing the database
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
23
Initializing the database
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.