SlideShare uma empresa Scribd logo
1 de 24
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.

Mais conteúdo relacionado

Mais procurados

Learn Entity Framework in a day with Code First, Model First and Database First
Learn Entity Framework in a day with Code First, Model First and Database FirstLearn Entity Framework in a day with Code First, Model First and Database First
Learn Entity Framework in a day with Code First, Model First and Database FirstJibran Rasheed Khan
 
Couchbase - Yet Another Introduction
Couchbase - Yet Another IntroductionCouchbase - Yet Another Introduction
Couchbase - Yet Another IntroductionKelum Senanayake
 
Using MongoDB with the .Net Framework
Using MongoDB with the .Net FrameworkUsing MongoDB with the .Net Framework
Using MongoDB with the .Net FrameworkStefano Paluello
 
Midterm presentation
Midterm presentationMidterm presentation
Midterm presentationdsmo223
 
The Economies of Scaling Software
The Economies of Scaling SoftwareThe Economies of Scaling Software
The Economies of Scaling SoftwareAbdelmonaim Remani
 
D2W Stateful Controllers
D2W Stateful ControllersD2W Stateful Controllers
D2W Stateful ControllersWO Community
 
Unit Testing with WOUnit
Unit Testing with WOUnitUnit Testing with WOUnit
Unit Testing with WOUnitWO Community
 
Serialization and performance in Java
Serialization and performance in JavaSerialization and performance in Java
Serialization and performance in JavaStrannik_2013
 
In memory OLAP engine
In memory OLAP engineIn memory OLAP engine
In memory OLAP engineWO Community
 
JavaScript, VBScript, AJAX, CGI
JavaScript, VBScript, AJAX, CGIJavaScript, VBScript, AJAX, CGI
JavaScript, VBScript, AJAX, CGIAashish Jain
 
Java 101 Intro to Java Programming
Java 101 Intro to Java ProgrammingJava 101 Intro to Java Programming
Java 101 Intro to Java Programmingagorolabs
 
Power shell basics day 3
Power shell basics day 3Power shell basics day 3
Power shell basics day 3Ashish Raj
 
New Features Of JDK 7
New Features Of JDK 7New Features Of JDK 7
New Features Of JDK 7Deniz Oguz
 
Mongo db rev001.
Mongo db rev001.Mongo db rev001.
Mongo db rev001.Rich Helton
 

Mais procurados (20)

Learn Entity Framework in a day with Code First, Model First and Database First
Learn Entity Framework in a day with Code First, Model First and Database FirstLearn Entity Framework in a day with Code First, Model First and Database First
Learn Entity Framework in a day with Code First, Model First and Database First
 
Couchbase - Yet Another Introduction
Couchbase - Yet Another IntroductionCouchbase - Yet Another Introduction
Couchbase - Yet Another Introduction
 
Node.js Introduction
Node.js IntroductionNode.js Introduction
Node.js Introduction
 
Life outside WO
Life outside WOLife outside WO
Life outside WO
 
Using MongoDB with the .Net Framework
Using MongoDB with the .Net FrameworkUsing MongoDB with the .Net Framework
Using MongoDB with the .Net Framework
 
Midterm presentation
Midterm presentationMidterm presentation
Midterm presentation
 
55 New Features in Java 7
55 New Features in Java 755 New Features in Java 7
55 New Features in Java 7
 
The Economies of Scaling Software
The Economies of Scaling SoftwareThe Economies of Scaling Software
The Economies of Scaling Software
 
Java JDBC
Java JDBCJava JDBC
Java JDBC
 
D2W Stateful Controllers
D2W Stateful ControllersD2W Stateful Controllers
D2W Stateful Controllers
 
Unit Testing with WOUnit
Unit Testing with WOUnitUnit Testing with WOUnit
Unit Testing with WOUnit
 
Serialization and performance in Java
Serialization and performance in JavaSerialization and performance in Java
Serialization and performance in Java
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
In memory OLAP engine
In memory OLAP engineIn memory OLAP engine
In memory OLAP engine
 
JavaScript, VBScript, AJAX, CGI
JavaScript, VBScript, AJAX, CGIJavaScript, VBScript, AJAX, CGI
JavaScript, VBScript, AJAX, CGI
 
Java 101 Intro to Java Programming
Java 101 Intro to Java ProgrammingJava 101 Intro to Java Programming
Java 101 Intro to Java Programming
 
Power shell basics day 3
Power shell basics day 3Power shell basics day 3
Power shell basics day 3
 
New Features Of JDK 7
New Features Of JDK 7New Features Of JDK 7
New Features Of JDK 7
 
Mongo db rev001.
Mongo db rev001.Mongo db rev001.
Mongo db rev001.
 
Smart Migration to JDK 8
Smart Migration to JDK 8Smart Migration to JDK 8
Smart Migration to JDK 8
 

Destaque

06 integrating extra features and looking forward
06   integrating extra features and looking forward06   integrating extra features and looking forward
06 integrating extra features and looking forwardМарина Босова
 
01 introduction to entity framework
01   introduction to entity framework01   introduction to entity framework
01 introduction to entity frameworkMaxim Shaptala
 
001 hosting
001 hosting001 hosting
001 hostingsivorka
 
000 introduction
000 introduction000 introduction
000 introductionsivorka
 
C++ 11 Style : A Touch of Class
C++ 11 Style : A Touch of ClassC++ 11 Style : A Touch of Class
C++ 11 Style : A Touch of ClassYogendra Rampuria
 
Mva stf module 5 - rus
Mva stf module 5 - rusMva stf module 5 - rus
Mva stf module 5 - rusMaxim Shaptala
 
Mva stf module 6 - rus
Mva stf module 6 - rusMva stf module 6 - rus
Mva stf module 6 - rusMaxim Shaptala
 
презентация привязка модели и валидация данных
презентация   привязка модели и валидация данныхпрезентация   привязка модели и валидация данных
презентация привязка модели и валидация данныхsivorka
 
навигация и валидаторы презентация
навигация и валидаторы   презентациянавигация и валидаторы   презентация
навигация и валидаторы презентацияsivorka
 
05 cерверные элементы управления презентация
05 cерверные элементы управления   презентация05 cерверные элементы управления   презентация
05 cерверные элементы управления презентацияsivorka
 
Mva stf module 4 - rus
Mva stf module 4 - rusMva stf module 4 - rus
Mva stf module 4 - rusMaxim Shaptala
 
Mva stf module 3 - rus
Mva stf module 3 - rusMva stf module 3 - rus
Mva stf module 3 - rusMaxim Shaptala
 
Mva stf module 1 - rus
Mva stf module 1 - rusMva stf module 1 - rus
Mva stf module 1 - rusMaxim Shaptala
 
Mva stf module 2 - rus
Mva stf module 2 - rusMva stf module 2 - rus
Mva stf module 2 - rusMaxim Shaptala
 

Destaque (20)

03 managing relationships
03   managing relationships03   managing relationships
03 managing relationships
 
01 introduction to entity framework
01   introduction to entity framework01   introduction to entity framework
01 introduction to entity framework
 
04 managing the database
04   managing the database04   managing the database
04 managing the database
 
05 managing transactions
05   managing transactions05   managing transactions
05 managing transactions
 
06 integrating extra features and looking forward
06   integrating extra features and looking forward06   integrating extra features and looking forward
06 integrating extra features and looking forward
 
01 introduction to entity framework
01   introduction to entity framework01   introduction to entity framework
01 introduction to entity framework
 
Introduction to UML
Introduction to UMLIntroduction to UML
Introduction to UML
 
001 hosting
001 hosting001 hosting
001 hosting
 
000 introduction
000 introduction000 introduction
000 introduction
 
C++ 11 Style : A Touch of Class
C++ 11 Style : A Touch of ClassC++ 11 Style : A Touch of Class
C++ 11 Style : A Touch of Class
 
Mva stf module 5 - rus
Mva stf module 5 - rusMva stf module 5 - rus
Mva stf module 5 - rus
 
Mva stf module 6 - rus
Mva stf module 6 - rusMva stf module 6 - rus
Mva stf module 6 - rus
 
презентация привязка модели и валидация данных
презентация   привязка модели и валидация данныхпрезентация   привязка модели и валидация данных
презентация привязка модели и валидация данных
 
навигация и валидаторы презентация
навигация и валидаторы   презентациянавигация и валидаторы   презентация
навигация и валидаторы презентация
 
05 cерверные элементы управления презентация
05 cерверные элементы управления   презентация05 cерверные элементы управления   презентация
05 cерверные элементы управления презентация
 
Mva stf module 4 - rus
Mva stf module 4 - rusMva stf module 4 - rus
Mva stf module 4 - rus
 
Mva stf module 3 - rus
Mva stf module 3 - rusMva stf module 3 - rus
Mva stf module 3 - rus
 
Testing po
Testing poTesting po
Testing po
 
Mva stf module 1 - rus
Mva stf module 1 - rusMva stf module 1 - rus
Mva stf module 1 - rus
 
Mva stf module 2 - rus
Mva stf module 2 - rusMva stf module 2 - rus
Mva stf module 2 - rus
 

Semelhante a 02 beginning code first

dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...dotNet Miami
 
Entity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic UnicornsEntity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic UnicornsRichie Rump
 
Yapc10 Cdt World Domination
Yapc10   Cdt World DominationYapc10   Cdt World Domination
Yapc10 Cdt World DominationcPanel
 
Sterling for Windows Phone 7
Sterling for Windows Phone 7Sterling for Windows Phone 7
Sterling for Windows Phone 7Jeremy Likness
 
Hibernate in XPages
Hibernate in XPagesHibernate in XPages
Hibernate in XPagesToby Samples
 
Modeling Tricks My Relational Database Never Taught Me
Modeling Tricks My Relational Database Never Taught MeModeling Tricks My Relational Database Never Taught Me
Modeling Tricks My Relational Database Never Taught MeDavid Boike
 
Lessons from a Dying CMS
Lessons from a Dying CMSLessons from a Dying CMS
Lessons from a Dying CMSSandy Smith
 
Rails Tips and Best Practices
Rails Tips and Best PracticesRails Tips and Best Practices
Rails Tips and Best PracticesDavid Keener
 
Webinar: What's new in the .NET Driver
Webinar: What's new in the .NET DriverWebinar: What's new in the .NET Driver
Webinar: What's new in the .NET DriverMongoDB
 
Jdbc Java Programming
Jdbc Java ProgrammingJdbc Java Programming
Jdbc Java Programmingchhaichivon
 
Machine Learning with ML.NET and Azure - Andy Cross
Machine Learning with ML.NET and Azure - Andy CrossMachine Learning with ML.NET and Azure - Andy Cross
Machine Learning with ML.NET and Azure - Andy CrossAndrew Flatters
 
Modules Building Presentation
Modules Building PresentationModules Building Presentation
Modules Building Presentationhtyson
 
Database continuous integration, unit test and functional test
Database continuous integration, unit test and functional testDatabase continuous integration, unit test and functional test
Database continuous integration, unit test and functional testHarry Zheng
 
Raffaele Rialdi
Raffaele RialdiRaffaele Rialdi
Raffaele RialdiCodeFest
 
My first powershell script
My first powershell scriptMy first powershell script
My first powershell scriptDavid Cobb
 
Examiness hints and tips from the trenches
Examiness hints and tips from the trenchesExaminess hints and tips from the trenches
Examiness hints and tips from the trenchesIsmail Mayat
 
Practical Malware Analysis: Ch 10: Kernel Debugging with WinDbg
Practical Malware Analysis: Ch 10: Kernel Debugging with WinDbgPractical Malware Analysis: Ch 10: Kernel Debugging with WinDbg
Practical Malware Analysis: Ch 10: Kernel Debugging with WinDbgSam Bowne
 

Semelhante a 02 beginning code first (20)

dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and M...
 
Entity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic UnicornsEntity Framework: Code First and Magic Unicorns
Entity Framework: Code First and Magic Unicorns
 
05 entity framework
05 entity framework05 entity framework
05 entity framework
 
Yapc10 Cdt World Domination
Yapc10   Cdt World DominationYapc10   Cdt World Domination
Yapc10 Cdt World Domination
 
Sterling for Windows Phone 7
Sterling for Windows Phone 7Sterling for Windows Phone 7
Sterling for Windows Phone 7
 
Hibernate in XPages
Hibernate in XPagesHibernate in XPages
Hibernate in XPages
 
Modeling Tricks My Relational Database Never Taught Me
Modeling Tricks My Relational Database Never Taught MeModeling Tricks My Relational Database Never Taught Me
Modeling Tricks My Relational Database Never Taught Me
 
Real World MVC
Real World MVCReal World MVC
Real World MVC
 
Lessons from a Dying CMS
Lessons from a Dying CMSLessons from a Dying CMS
Lessons from a Dying CMS
 
Rails Tips and Best Practices
Rails Tips and Best PracticesRails Tips and Best Practices
Rails Tips and Best Practices
 
Webinar: What's new in the .NET Driver
Webinar: What's new in the .NET DriverWebinar: What's new in the .NET Driver
Webinar: What's new in the .NET Driver
 
Jdbc Java Programming
Jdbc Java ProgrammingJdbc Java Programming
Jdbc Java Programming
 
Machine Learning with ML.NET and Azure - Andy Cross
Machine Learning with ML.NET and Azure - Andy CrossMachine Learning with ML.NET and Azure - Andy Cross
Machine Learning with ML.NET and Azure - Andy Cross
 
Modules Building Presentation
Modules Building PresentationModules Building Presentation
Modules Building Presentation
 
Database continuous integration, unit test and functional test
Database continuous integration, unit test and functional testDatabase continuous integration, unit test and functional test
Database continuous integration, unit test and functional test
 
Raffaele Rialdi
Raffaele RialdiRaffaele Rialdi
Raffaele Rialdi
 
My first powershell script
My first powershell scriptMy first powershell script
My first powershell script
 
Examiness hints and tips from the trenches
Examiness hints and tips from the trenchesExaminess hints and tips from the trenches
Examiness hints and tips from the trenches
 
La sql
La sqlLa sql
La sql
 
Practical Malware Analysis: Ch 10: Kernel Debugging with WinDbg
Practical Malware Analysis: Ch 10: Kernel Debugging with WinDbgPractical Malware Analysis: Ch 10: Kernel Debugging with WinDbg
Practical Malware Analysis: Ch 10: Kernel Debugging with WinDbg
 

Último

The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxShobhayan Kirtania
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 

Último (20)

The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptx
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 

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.

Notas do Editor

  1. 1