SlideShare a Scribd company logo
02 | Beginning Code First
Adam Tuliper | Technical Evangelist
Christopher Harrison | Content Developer
• Simple Code First
• Creating classes
• Creating Data Context
• Initializing the database
Code First
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 standard conventions
– 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
– Name
Strings
• Nullable nvarchar(max) is the default
• Attributes
– StringLengthAttribute
• MaximumLength
• MinimumLength
– RequiredAttribute
Numbers
• SQL data type is mapped to .NET data type
– long becomes BigInt
• RangeAttribute
– Maximum
– Minimum
Value types and nullability
• Dates and numbers are value types in .NET
• Value type properties must be marked as nullable
– Nullable<T>
– type?
DEMO
Attributes and database control
(warning... This demo is going to fail. Well, sort of.)
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; }
}
DEMO
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
DEMO
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
DEMO
Initializing the database
©2013 Microsoft Corporation. All rights reserved. Microsoft, Windows, Office, Azure, System Center, Dynamics and other product names are or may be registered trademarks and/or trademarks in the
U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft
must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after
the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

More Related Content

PPTX
Drupal 6 to 7 migration
PPTX
Intro to java programming
PDF
Running DSpace: Technical overview, lessons learned, workflows and essential ...
PDF
Elasticsearch in Production (London version)
PDF
Extbase object to xml mapping
KEY
Modules Building Presentation
PPTX
Web Ninja
Drupal 6 to 7 migration
Intro to java programming
Running DSpace: Technical overview, lessons learned, workflows and essential ...
Elasticsearch in Production (London version)
Extbase object to xml mapping
Modules Building Presentation
Web Ninja

What's hot (20)

PDF
Elasticsearch Basics
PPTX
Pass by value and pass by reference
PPTX
MongoDB
PDF
Building a Lightweight Discovery Interface for China's Patents@NYC Solr/Lucen...
PDF
ElasticSearch: Distributed Multitenant NoSQL Datastore and Search Engine
PDF
Elasticsearch 101 - Cluster setup and tuning
PDF
Why CouchDB
PPTX
Elastic Search
PPTX
ElasticSearch in Production: lessons learned
PDF
ODP
KEY
Object oriented javascript
KEY
Preliminary committee presentation
PDF
Drupal Developer Skills (2012) - DrupalCamp LA 2012
PPTX
NOSQL Databases for the .NET Developer
PPTX
Why databases cry at night
PPTX
Eurydike: Schemaless Object Relational SQL Mapper
PPTX
Day 4 - Models
PPTX
Intro to RavenDB
PPTX
Introducing prefLabel.org
Elasticsearch Basics
Pass by value and pass by reference
MongoDB
Building a Lightweight Discovery Interface for China's Patents@NYC Solr/Lucen...
ElasticSearch: Distributed Multitenant NoSQL Datastore and Search Engine
Elasticsearch 101 - Cluster setup and tuning
Why CouchDB
Elastic Search
ElasticSearch in Production: lessons learned
Object oriented javascript
Preliminary committee presentation
Drupal Developer Skills (2012) - DrupalCamp LA 2012
NOSQL Databases for the .NET Developer
Why databases cry at night
Eurydike: Schemaless Object Relational SQL Mapper
Day 4 - Models
Intro to RavenDB
Introducing prefLabel.org
Ad

Viewers also liked (6)

PPT
14 questoes para_ateus
PPTX
Pinterest walkthrough
DOCX
Il mostro di fi renzi
PPTX
Физичке и хемијске промене
PPTX
Catalogo de tarjetas navideñas
DOCX
Ruth Rodriguez Resume 2
14 questoes para_ateus
Pinterest walkthrough
Il mostro di fi renzi
Физичке и хемијске промене
Catalogo de tarjetas navideñas
Ruth Rodriguez Resume 2
Ad

Similar to 02 beginning code first (20)

PPTX
Ef code first
PPTX
Entity framework
PPTX
Entity Framework: Code First and Magic Unicorns
PPTX
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
PPT
Entity frameworks101
PDF
Intake 38 data access 5
DOCX
MVC Application using EntityFramework Code-First approach Part4
PPTX
01 introduction to entity framework
PPTX
01 introduction to entity framework
PPTX
Applying EF Code First at Your Job
PDF
Intake 37 ef2
PPTX
Entity Framework: Nakov @ BFU Hackhaton 2015
PPSX
Seesion 7 ASP.Net (MVC) Model
PDF
Murach: How to use Entity Framework EF Core
PPTX
Entity Framework Today (May 2012)
PPTX
Entity framework code first
PDF
.NET Core, ASP.NET Core Course, Session 13
PPTX
Entity Frame Work Core.pptx
PDF
Learn Entity Framework in a day with Code First, Model First and Database First
PPTX
Getting started with entity framework
Ef code first
Entity framework
Entity Framework: Code First and Magic Unicorns
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
Entity frameworks101
Intake 38 data access 5
MVC Application using EntityFramework Code-First approach Part4
01 introduction to entity framework
01 introduction to entity framework
Applying EF Code First at Your Job
Intake 37 ef2
Entity Framework: Nakov @ BFU Hackhaton 2015
Seesion 7 ASP.Net (MVC) Model
Murach: How to use Entity Framework EF Core
Entity Framework Today (May 2012)
Entity framework code first
.NET Core, ASP.NET Core Course, Session 13
Entity Frame Work Core.pptx
Learn Entity Framework in a day with Code First, Model First and Database First
Getting started with entity framework

More from Maxim Shaptala (8)

PPTX
Mva stf module 6 - rus
PPTX
Mva stf module 5 - rus
PPTX
Mva stf module 4 - rus
PPTX
Mva stf module 3 - rus
PPTX
Mva stf module 2 - rus
PPTX
Mva stf module 1 - rus
PPTX
file handling in c
PPTX
file handling in c++
Mva stf module 6 - rus
Mva stf module 5 - rus
Mva stf module 4 - rus
Mva stf module 3 - rus
Mva stf module 2 - rus
Mva stf module 1 - rus
file handling in c
file handling in c++

Recently uploaded (20)

PDF
System and Network Administration Chapter 2
PPT
Introduction Database Management System for Course Database
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PPTX
Odoo POS Development Services by CandidRoot Solutions
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PPTX
ISO 45001 Occupational Health and Safety Management System
PDF
2025 Textile ERP Trends: SAP, Odoo & Oracle
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PPTX
CHAPTER 2 - PM Management and IT Context
PPTX
ai tools demonstartion for schools and inter college
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PPTX
ManageIQ - Sprint 268 Review - Slide Deck
PPTX
Introduction to Artificial Intelligence
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
System and Network Administraation Chapter 3
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
System and Network Administration Chapter 2
Introduction Database Management System for Course Database
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Odoo POS Development Services by CandidRoot Solutions
Design an Analysis of Algorithms II-SECS-1021-03
ISO 45001 Occupational Health and Safety Management System
2025 Textile ERP Trends: SAP, Odoo & Oracle
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
CHAPTER 2 - PM Management and IT Context
ai tools demonstartion for schools and inter college
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
ManageIQ - Sprint 268 Review - Slide Deck
Introduction to Artificial Intelligence
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PTS Company Brochure 2025 (1).pdf.......
System and Network Administraation Chapter 3
VVF-Customer-Presentation2025-Ver1.9.pptx
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Which alternative to Crystal Reports is best for small or large businesses.pdf
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool

02 beginning code first

  • 1. 02 | Beginning Code First Adam Tuliper | Technical Evangelist Christopher Harrison | Content Developer
  • 2. • Simple Code First • Creating classes • Creating Data Context • Initializing the database Code First
  • 4. public class Artist { public int ArtistID { get; set; } public string Name { get; set; } public string Bio { get; set; } }
  • 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
  • 11. Table creation • TableAttribute – Schema – Name • ColumnAttribute – Name
  • 12. Strings • Nullable nvarchar(max) is the default • Attributes – StringLengthAttribute • MaximumLength • MinimumLength – RequiredAttribute
  • 13. Numbers • SQL data type is mapped to .NET data type – long becomes BigInt • RangeAttribute – Maximum – Minimum
  • 14. Value types and nullability • Dates and numbers are value types in .NET • Value type properties must be marked as nullable – Nullable<T> – type?
  • 15. DEMO Attributes and database control (warning... This demo is going to fail. Well, sort of.)
  • 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; } }
  • 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
  • 24. ©2013 Microsoft Corporation. All rights reserved. Microsoft, Windows, Office, Azure, System Center, Dynamics and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Editor's Notes