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

Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...JojoEDelaCruz
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 

Último (20)

Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 

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