SlideShare a Scribd company logo
04 | Managing the Database
Adam Tuliper | Technical Evangelist, Microsoft
Christopher Harrison | Content Developer, Microsoft
Module Overview
• Fluent API
• Code First Migrations
Fluent API
Data Annotations vs Fluent API
• Why use data annotations (attributes)?
– Simple, works well for basic scenarios
– Some like attributes where they affect properties
– Integrates with MVC validation
• Why use Fluent API?
– Keeps domain classes clean - configuration in separate section
– More supported operations (advanced mappings, datetime precision, fixed
length and non-Unicode strings, etc)
– Using view models for views? Use Fluent for domain entities
– Fluent API allows very readable method cascading
• builder.Entity<Album>().Property(t => t.Name).IsRequired().HasMaxLength(60);
Separate Fluent & Data Annotations
• EF recognizes subset
– StringLength
– Range
– Required
– MinLength
– MaxLength
• This works, but purists may have a problem
– Mixes persistence, presentation, and validation logic
Using Fluent API without Data Annotations?
• How would we validate then?
• We would
– Map view model to Entity
– Save Entity
– Catch DbEntityValidationException
– Add errors to ModelState
• See code comments
What does Fluent Api support?
• Easily remapping legacy names to code names
– Customer.Unique_ID Customer.CustomerId
– ShipInfo.Unique_ID to ShipInfo.ShipInfoId
• Single type to multiple tables, vice versa
• Schema mapping
• Mapping table per type, table per class, entity & table splitting
• keys, length, index
OnModelCreating
• Override OnModelCreating in DbContext
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("MusicStore");
modelBuilder.Entity<Album>()
.Property(e => e.Title)
.HasColumnName("Album_Title");
modelBuilder.Entity<Album>()
.HasRequired<Artist>(s => s.Artist)
.WithMany(s => s.Albums);
}
DEMODEMO
Fluent API Basics
Remapping legacy tables
• Often legacy databases use ‘bad’ naming conventions
• Fluent API allows mapping scenarios
– Any column name to any field
– Table per type - subclasses have their own table ex Animal, Cat, Dog
– Table per class
– Entity splitting – multiple entities per table
– Table Splitting- multiple tables per entity
DEMODEMO
Fluent API Remapping tables and columns
Code First Migrations
Traditional DB/Code Management
• We can manage databases for our apps in many ways
• Create code, write sql, create database
• Create database, write code, script database
DEMODEMO
Manual Script Management
What’s the problem?
• Keeping code and database in sync was issue
• Managing versions requires significant manual effort
• Typically ‘undo’ scripts aren’t created
• Ensuring app version matches database version
– Ever forget/lose a script?
• Fix issues (many ‘went to production’ bugs)
– string customer; didn’t validate to varchar(50)
What would help?
• Our apps run code that maps between database and code
– Definition of ORM
• We write code, would be nice to have feature to manage scripts
– This is where Code First applies
What are code first migrations?
• Provides a way to manage dev cycle between code & db
• Allows you to
– Create point in time snapshots as ‘migrations’
– Generate scripts to sync code and database
– Allows migrating & scripting SQL between various snapshots
– Including upgrading and downgrading
• Can this help for existing databases?
– Code or reverse engineer into models, add migration
– Add-Migration Initial –IgnoreChanges
How do Code First Migrations work?
• Code created under default Migrations folder
• Each new Migration (add-migration) adds new code
• Can overwrite/update existing migrations
– Add-migration AddedShipInfo
– Developer adds more properties to ShipInfo class
– Add-migration AddedShipInfo (updates existing migration)
• Push to database
– Update-database -script
• Can configure automatic migrations
DEMODEMO
Setting up migrations
DEMODEMO
Customizing Migrations
DEMODEMO
Managing an existing database
Resources
• Code first migrations in team environments
– https://msdn.microsoft.com/en-us/data/dn481501.aspx
• Configuring/Mapping Properties and Types with the Fluent API
– https://msdn.microsoft.com/en-us/data/jj591617.aspx
©2014 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.
©2014 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

What's hot

Five Enterprise Best Practices That EVERY Salesforce Org Can Use (DF15 Session)
Five Enterprise Best Practices That EVERY Salesforce Org Can Use (DF15 Session)Five Enterprise Best Practices That EVERY Salesforce Org Can Use (DF15 Session)
Five Enterprise Best Practices That EVERY Salesforce Org Can Use (DF15 Session)
Vivek Chawla
 
Angular jS Introduction by Google
Angular jS Introduction by GoogleAngular jS Introduction by Google
Angular jS Introduction by Google
ASG
 
Abstract #236765 advanced essbase java api tips and tricks
Abstract #236765 advanced essbase java api tips and tricksAbstract #236765 advanced essbase java api tips and tricks
Abstract #236765 advanced essbase java api tips and trickstimtow
 
The New Way of Developing with AEM 6.0 | Sightly | Beautiful Markup
The New Way of Developing with AEM 6.0 | Sightly | Beautiful MarkupThe New Way of Developing with AEM 6.0 | Sightly | Beautiful Markup
The New Way of Developing with AEM 6.0 | Sightly | Beautiful MarkupSenol Tas
 
When Sightly Meets Slice by Tomasz Niedźwiedź
When Sightly Meets Slice by Tomasz NiedźwiedźWhen Sightly Meets Slice by Tomasz Niedźwiedź
When Sightly Meets Slice by Tomasz Niedźwiedź
AEM HUB
 
Introducing domain driven design - dogfood con 2018
Introducing domain driven design - dogfood con 2018Introducing domain driven design - dogfood con 2018
Introducing domain driven design - dogfood con 2018
Steven Smith
 
Optimus XPages: An Explosion of Techniques and Best Practices
Optimus XPages: An Explosion of Techniques and Best PracticesOptimus XPages: An Explosion of Techniques and Best Practices
Optimus XPages: An Explosion of Techniques and Best Practices
Teamstudio
 
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Steven Smith
 
Salesforce Coding techniques that keep your admins happy (DF13)
Salesforce Coding techniques that keep your admins happy (DF13)Salesforce Coding techniques that keep your admins happy (DF13)
Salesforce Coding techniques that keep your admins happy (DF13)
Roy Gilad
 
Introduction to Ibatis by Rohit
Introduction to Ibatis by RohitIntroduction to Ibatis by Rohit
Introduction to Ibatis by Rohit
Rohit Prabhakar
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
ASG
 
Oracle SQL Developer Reports
Oracle SQL Developer ReportsOracle SQL Developer Reports
Oracle SQL Developer Reports
Jeff Smith
 
Salesforce Basic Development
Salesforce Basic DevelopmentSalesforce Basic Development
Salesforce Basic Development
Naveen Dhanaraj
 
MWLUG - Universal Java
MWLUG  -  Universal JavaMWLUG  -  Universal Java
MWLUG - Universal Java
Philippe Riand
 
Unit Tests are Overrated (NDCOslo 2013)
Unit Tests are Overrated (NDCOslo 2013)Unit Tests are Overrated (NDCOslo 2013)
Unit Tests are Overrated (NDCOslo 2013)
Lars-Erik Kindblad
 
Azure rev002
Azure rev002Azure rev002
Azure rev002
Rich Helton
 
Onion Architecture / Clean Architecture
Onion Architecture / Clean ArchitectureOnion Architecture / Clean Architecture
Onion Architecture / Clean Architecture
Attila Bertók
 
JavaScript Frameworks and Java EE – A Great Match
JavaScript Frameworks and Java EE – A Great MatchJavaScript Frameworks and Java EE – A Great Match
JavaScript Frameworks and Java EE – A Great Match
Reza Rahman
 
Microsoft for developers open source and cross platform
Microsoft for developers  open source and cross platformMicrosoft for developers  open source and cross platform
Microsoft for developers open source and cross platform
Julie Lerman
 
Data normalization across API interactions
Data normalization across API interactionsData normalization across API interactions
Data normalization across API interactions
Cloud Elements
 

What's hot (20)

Five Enterprise Best Practices That EVERY Salesforce Org Can Use (DF15 Session)
Five Enterprise Best Practices That EVERY Salesforce Org Can Use (DF15 Session)Five Enterprise Best Practices That EVERY Salesforce Org Can Use (DF15 Session)
Five Enterprise Best Practices That EVERY Salesforce Org Can Use (DF15 Session)
 
Angular jS Introduction by Google
Angular jS Introduction by GoogleAngular jS Introduction by Google
Angular jS Introduction by Google
 
Abstract #236765 advanced essbase java api tips and tricks
Abstract #236765 advanced essbase java api tips and tricksAbstract #236765 advanced essbase java api tips and tricks
Abstract #236765 advanced essbase java api tips and tricks
 
The New Way of Developing with AEM 6.0 | Sightly | Beautiful Markup
The New Way of Developing with AEM 6.0 | Sightly | Beautiful MarkupThe New Way of Developing with AEM 6.0 | Sightly | Beautiful Markup
The New Way of Developing with AEM 6.0 | Sightly | Beautiful Markup
 
When Sightly Meets Slice by Tomasz Niedźwiedź
When Sightly Meets Slice by Tomasz NiedźwiedźWhen Sightly Meets Slice by Tomasz Niedźwiedź
When Sightly Meets Slice by Tomasz Niedźwiedź
 
Introducing domain driven design - dogfood con 2018
Introducing domain driven design - dogfood con 2018Introducing domain driven design - dogfood con 2018
Introducing domain driven design - dogfood con 2018
 
Optimus XPages: An Explosion of Techniques and Best Practices
Optimus XPages: An Explosion of Techniques and Best PracticesOptimus XPages: An Explosion of Techniques and Best Practices
Optimus XPages: An Explosion of Techniques and Best Practices
 
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
 
Salesforce Coding techniques that keep your admins happy (DF13)
Salesforce Coding techniques that keep your admins happy (DF13)Salesforce Coding techniques that keep your admins happy (DF13)
Salesforce Coding techniques that keep your admins happy (DF13)
 
Introduction to Ibatis by Rohit
Introduction to Ibatis by RohitIntroduction to Ibatis by Rohit
Introduction to Ibatis by Rohit
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Oracle SQL Developer Reports
Oracle SQL Developer ReportsOracle SQL Developer Reports
Oracle SQL Developer Reports
 
Salesforce Basic Development
Salesforce Basic DevelopmentSalesforce Basic Development
Salesforce Basic Development
 
MWLUG - Universal Java
MWLUG  -  Universal JavaMWLUG  -  Universal Java
MWLUG - Universal Java
 
Unit Tests are Overrated (NDCOslo 2013)
Unit Tests are Overrated (NDCOslo 2013)Unit Tests are Overrated (NDCOslo 2013)
Unit Tests are Overrated (NDCOslo 2013)
 
Azure rev002
Azure rev002Azure rev002
Azure rev002
 
Onion Architecture / Clean Architecture
Onion Architecture / Clean ArchitectureOnion Architecture / Clean Architecture
Onion Architecture / Clean Architecture
 
JavaScript Frameworks and Java EE – A Great Match
JavaScript Frameworks and Java EE – A Great MatchJavaScript Frameworks and Java EE – A Great Match
JavaScript Frameworks and Java EE – A Great Match
 
Microsoft for developers open source and cross platform
Microsoft for developers  open source and cross platformMicrosoft for developers  open source and cross platform
Microsoft for developers open source and cross platform
 
Data normalization across API interactions
Data normalization across API interactionsData normalization across API interactions
Data normalization across API interactions
 

Viewers also liked

03 managing relationships
03   managing relationships03   managing relationships
03 managing relationships
Марина Босова
 
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
Марина Босова
 
02 beginning code first
02   beginning code first02   beginning code first
02 beginning code first
Марина Босова
 
Introduction to UML
Introduction to UMLIntroduction to UML
01 introduction to entity framework
01   introduction to entity framework01   introduction to entity framework
01 introduction to entity framework
Maxim Shaptala
 
001 hosting
001 hosting001 hosting
001 hosting
sivorka
 
000 introduction
000 introduction000 introduction
000 introduction
sivorka
 
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
Yogendra Rampuria
 
навигация и валидаторы презентация
навигация и валидаторы   презентациянавигация и валидаторы   презентация
навигация и валидаторы презентация
sivorka
 
Mva stf module 5 - rus
Mva stf module 5 - rusMva stf module 5 - rus
Mva stf module 5 - rus
Maxim Shaptala
 
05 cерверные элементы управления презентация
05 cерверные элементы управления   презентация05 cерверные элементы управления   презентация
05 cерверные элементы управления презентация
sivorka
 
Mva stf module 6 - rus
Mva stf module 6 - rusMva stf module 6 - rus
Mva stf module 6 - rus
Maxim Shaptala
 
презентация привязка модели и валидация данных
презентация   привязка модели и валидация данныхпрезентация   привязка модели и валидация данных
презентация привязка модели и валидация данных
sivorka
 
Testing po
Testing poTesting po
Testing po
Marina Bosova
 
Mva stf module 3 - rus
Mva stf module 3 - rusMva stf module 3 - rus
Mva stf module 3 - rus
Maxim Shaptala
 
Mva stf module 2 - rus
Mva stf module 2 - rusMva stf module 2 - rus
Mva stf module 2 - rus
Maxim Shaptala
 
Mva stf module 1 - rus
Mva stf module 1 - rusMva stf module 1 - rus
Mva stf module 1 - rus
Maxim Shaptala
 
Mva stf module 4 - rus
Mva stf module 4 - rusMva stf module 4 - rus
Mva stf module 4 - rus
Maxim Shaptala
 
Getting started with angular js
Getting started with angular jsGetting started with angular js
Getting started with angular js
Maurice De Beijer [MVP]
 

Viewers also liked (20)

03 managing relationships
03   managing relationships03   managing relationships
03 managing relationships
 
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
 
02 beginning code first
02   beginning code first02   beginning code first
02 beginning code first
 
Introduction to UML
Introduction to UMLIntroduction to UML
Introduction to UML
 
01 introduction to entity framework
01   introduction to entity framework01   introduction to entity framework
01 introduction to entity framework
 
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
 
05 cерверные элементы управления презентация
05 cерверные элементы управления   презентация05 cерверные элементы управления   презентация
05 cерверные элементы управления презентация
 
Mva stf module 6 - rus
Mva stf module 6 - rusMva stf module 6 - rus
Mva stf module 6 - rus
 
презентация привязка модели и валидация данных
презентация   привязка модели и валидация данныхпрезентация   привязка модели и валидация данных
презентация привязка модели и валидация данных
 
Testing po
Testing poTesting po
Testing po
 
Mva stf module 3 - rus
Mva stf module 3 - rusMva stf module 3 - rus
Mva stf module 3 - rus
 
Mva stf module 2 - rus
Mva stf module 2 - rusMva stf module 2 - rus
Mva stf module 2 - rus
 
Mva stf module 1 - rus
Mva stf module 1 - rusMva stf module 1 - rus
Mva stf module 1 - rus
 
Mva stf module 4 - rus
Mva stf module 4 - rusMva stf module 4 - rus
Mva stf module 4 - rus
 
Getting started with angular js
Getting started with angular jsGetting started with angular js
Getting started with angular js
 

Similar to 04 managing the database

Migration Approaches for FDMEE
Migration Approaches for FDMEEMigration Approaches for FDMEE
Migration Approaches for FDMEE
Alithya
 
AWS Summit Singapore - Managing a Database Migration Project | Best Practices
AWS Summit Singapore - Managing a Database Migration Project | Best PracticesAWS Summit Singapore - Managing a Database Migration Project | Best Practices
AWS Summit Singapore - Managing a Database Migration Project | Best Practices
Amazon Web Services
 
AWS Summit Singapore Webinar Edition | Architecting a Serverless Data Lake on...
AWS Summit Singapore Webinar Edition | Architecting a Serverless Data Lake on...AWS Summit Singapore Webinar Edition | Architecting a Serverless Data Lake on...
AWS Summit Singapore Webinar Edition | Architecting a Serverless Data Lake on...
Amazon Web Services
 
1588487811-chp-11-c-enterprise-application-integration.ppt
1588487811-chp-11-c-enterprise-application-integration.ppt1588487811-chp-11-c-enterprise-application-integration.ppt
1588487811-chp-11-c-enterprise-application-integration.ppt
KalsoomTahir2
 
--Enterprise-Application-Integration.ppt
--Enterprise-Application-Integration.ppt--Enterprise-Application-Integration.ppt
--Enterprise-Application-Integration.ppt
eddielyndacanay0
 
SAP Business Objects Trianing
SAP Business Objects TrianingSAP Business Objects Trianing
Practical management of development & QA environments for SharePoint 2013
Practical management of development & QA environments for SharePoint 2013Practical management of development & QA environments for SharePoint 2013
Practical management of development & QA environments for SharePoint 2013
SharePointRadi
 
AIR - Framework ( Cairngorm and Parsley )
AIR - Framework ( Cairngorm and Parsley )AIR - Framework ( Cairngorm and Parsley )
AIR - Framework ( Cairngorm and Parsley )
senthil0809
 
Pramodkumar_SQL_DBA(5YRS EXP)
Pramodkumar_SQL_DBA(5YRS EXP)Pramodkumar_SQL_DBA(5YRS EXP)
Pramodkumar_SQL_DBA(5YRS EXP)pramod singh
 
Enterprise Data Integration for Microsoft Dynamics CRM
Enterprise Data Integration for Microsoft Dynamics CRMEnterprise Data Integration for Microsoft Dynamics CRM
Enterprise Data Integration for Microsoft Dynamics CRM
Daniel Cai
 
Infrastructure as Code - Getting Started, Concepts & Tools
Infrastructure as Code - Getting Started, Concepts & ToolsInfrastructure as Code - Getting Started, Concepts & Tools
Infrastructure as Code - Getting Started, Concepts & Tools
Lior Kamrat
 
DevOps in the Cloud with Microsoft Azure
DevOps in the Cloud with Microsoft AzureDevOps in the Cloud with Microsoft Azure
DevOps in the Cloud with Microsoft Azure
gjuljo
 
AmaleswaraRao_DOTNET
AmaleswaraRao_DOTNETAmaleswaraRao_DOTNET
AmaleswaraRao_DOTNETAmal J
 
Jesy George_CV_LATEST
Jesy George_CV_LATESTJesy George_CV_LATEST
Jesy George_CV_LATESTJesy George
 
Isset Presentation @ EECI2009
Isset Presentation @ EECI2009Isset Presentation @ EECI2009
Isset Presentation @ EECI2009
Isset Internet Professionals
 
Managing Your Cloud Assets
Managing Your Cloud AssetsManaging Your Cloud Assets
Managing Your Cloud Assets
Amazon Web Services
 
Metadata Modeling Best Practices with IBM Cognos Framework Manager
Metadata Modeling Best Practices with IBM Cognos Framework ManagerMetadata Modeling Best Practices with IBM Cognos Framework Manager
Metadata Modeling Best Practices with IBM Cognos Framework Manager
Senturus
 
Was l iberty for java batch and jsr352
Was l iberty for java batch and jsr352Was l iberty for java batch and jsr352
Was l iberty for java batch and jsr352sflynn073
 

Similar to 04 managing the database (20)

Migration Approaches for FDMEE
Migration Approaches for FDMEEMigration Approaches for FDMEE
Migration Approaches for FDMEE
 
AWS Summit Singapore - Managing a Database Migration Project | Best Practices
AWS Summit Singapore - Managing a Database Migration Project | Best PracticesAWS Summit Singapore - Managing a Database Migration Project | Best Practices
AWS Summit Singapore - Managing a Database Migration Project | Best Practices
 
AWS Summit Singapore Webinar Edition | Architecting a Serverless Data Lake on...
AWS Summit Singapore Webinar Edition | Architecting a Serverless Data Lake on...AWS Summit Singapore Webinar Edition | Architecting a Serverless Data Lake on...
AWS Summit Singapore Webinar Edition | Architecting a Serverless Data Lake on...
 
1588487811-chp-11-c-enterprise-application-integration.ppt
1588487811-chp-11-c-enterprise-application-integration.ppt1588487811-chp-11-c-enterprise-application-integration.ppt
1588487811-chp-11-c-enterprise-application-integration.ppt
 
--Enterprise-Application-Integration.ppt
--Enterprise-Application-Integration.ppt--Enterprise-Application-Integration.ppt
--Enterprise-Application-Integration.ppt
 
SAP Business Objects Trianing
SAP Business Objects TrianingSAP Business Objects Trianing
SAP Business Objects Trianing
 
Practical management of development & QA environments for SharePoint 2013
Practical management of development & QA environments for SharePoint 2013Practical management of development & QA environments for SharePoint 2013
Practical management of development & QA environments for SharePoint 2013
 
AIR - Framework ( Cairngorm and Parsley )
AIR - Framework ( Cairngorm and Parsley )AIR - Framework ( Cairngorm and Parsley )
AIR - Framework ( Cairngorm and Parsley )
 
Pramodkumar_SQL_DBA(5YRS EXP)
Pramodkumar_SQL_DBA(5YRS EXP)Pramodkumar_SQL_DBA(5YRS EXP)
Pramodkumar_SQL_DBA(5YRS EXP)
 
harish_resume
harish_resumeharish_resume
harish_resume
 
Enterprise Data Integration for Microsoft Dynamics CRM
Enterprise Data Integration for Microsoft Dynamics CRMEnterprise Data Integration for Microsoft Dynamics CRM
Enterprise Data Integration for Microsoft Dynamics CRM
 
Infrastructure as Code - Getting Started, Concepts & Tools
Infrastructure as Code - Getting Started, Concepts & ToolsInfrastructure as Code - Getting Started, Concepts & Tools
Infrastructure as Code - Getting Started, Concepts & Tools
 
It recruitments
It recruitmentsIt recruitments
It recruitments
 
DevOps in the Cloud with Microsoft Azure
DevOps in the Cloud with Microsoft AzureDevOps in the Cloud with Microsoft Azure
DevOps in the Cloud with Microsoft Azure
 
AmaleswaraRao_DOTNET
AmaleswaraRao_DOTNETAmaleswaraRao_DOTNET
AmaleswaraRao_DOTNET
 
Jesy George_CV_LATEST
Jesy George_CV_LATESTJesy George_CV_LATEST
Jesy George_CV_LATEST
 
Isset Presentation @ EECI2009
Isset Presentation @ EECI2009Isset Presentation @ EECI2009
Isset Presentation @ EECI2009
 
Managing Your Cloud Assets
Managing Your Cloud AssetsManaging Your Cloud Assets
Managing Your Cloud Assets
 
Metadata Modeling Best Practices with IBM Cognos Framework Manager
Metadata Modeling Best Practices with IBM Cognos Framework ManagerMetadata Modeling Best Practices with IBM Cognos Framework Manager
Metadata Modeling Best Practices with IBM Cognos Framework Manager
 
Was l iberty for java batch and jsr352
Was l iberty for java batch and jsr352Was l iberty for java batch and jsr352
Was l iberty for java batch and jsr352
 

Recently uploaded

How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
Celine George
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
Nguyen Thanh Tu Collection
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
bennyroshan06
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
Vivekanand Anglo Vedic Academy
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
PedroFerreira53928
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
PedroFerreira53928
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
AzmatAli747758
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 

Recently uploaded (20)

How to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERPHow to Create Map Views in the Odoo 17 ERP
How to Create Map Views in the Odoo 17 ERP
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 

04 managing the database

  • 1. 04 | Managing the Database Adam Tuliper | Technical Evangelist, Microsoft Christopher Harrison | Content Developer, Microsoft
  • 2. Module Overview • Fluent API • Code First Migrations
  • 4. Data Annotations vs Fluent API • Why use data annotations (attributes)? – Simple, works well for basic scenarios – Some like attributes where they affect properties – Integrates with MVC validation • Why use Fluent API? – Keeps domain classes clean - configuration in separate section – More supported operations (advanced mappings, datetime precision, fixed length and non-Unicode strings, etc) – Using view models for views? Use Fluent for domain entities – Fluent API allows very readable method cascading • builder.Entity<Album>().Property(t => t.Name).IsRequired().HasMaxLength(60);
  • 5. Separate Fluent & Data Annotations • EF recognizes subset – StringLength – Range – Required – MinLength – MaxLength • This works, but purists may have a problem – Mixes persistence, presentation, and validation logic
  • 6. Using Fluent API without Data Annotations? • How would we validate then? • We would – Map view model to Entity – Save Entity – Catch DbEntityValidationException – Add errors to ModelState • See code comments
  • 7. What does Fluent Api support? • Easily remapping legacy names to code names – Customer.Unique_ID Customer.CustomerId – ShipInfo.Unique_ID to ShipInfo.ShipInfoId • Single type to multiple tables, vice versa • Schema mapping • Mapping table per type, table per class, entity & table splitting • keys, length, index
  • 8. OnModelCreating • Override OnModelCreating in DbContext protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.HasDefaultSchema("MusicStore"); modelBuilder.Entity<Album>() .Property(e => e.Title) .HasColumnName("Album_Title"); modelBuilder.Entity<Album>() .HasRequired<Artist>(s => s.Artist) .WithMany(s => s.Albums); }
  • 10. Remapping legacy tables • Often legacy databases use ‘bad’ naming conventions • Fluent API allows mapping scenarios – Any column name to any field – Table per type - subclasses have their own table ex Animal, Cat, Dog – Table per class – Entity splitting – multiple entities per table – Table Splitting- multiple tables per entity
  • 11. DEMODEMO Fluent API Remapping tables and columns
  • 13. Traditional DB/Code Management • We can manage databases for our apps in many ways • Create code, write sql, create database • Create database, write code, script database
  • 15. What’s the problem? • Keeping code and database in sync was issue • Managing versions requires significant manual effort • Typically ‘undo’ scripts aren’t created • Ensuring app version matches database version – Ever forget/lose a script? • Fix issues (many ‘went to production’ bugs) – string customer; didn’t validate to varchar(50)
  • 16. What would help? • Our apps run code that maps between database and code – Definition of ORM • We write code, would be nice to have feature to manage scripts – This is where Code First applies
  • 17. What are code first migrations? • Provides a way to manage dev cycle between code & db • Allows you to – Create point in time snapshots as ‘migrations’ – Generate scripts to sync code and database – Allows migrating & scripting SQL between various snapshots – Including upgrading and downgrading • Can this help for existing databases? – Code or reverse engineer into models, add migration – Add-Migration Initial –IgnoreChanges
  • 18. How do Code First Migrations work? • Code created under default Migrations folder • Each new Migration (add-migration) adds new code • Can overwrite/update existing migrations – Add-migration AddedShipInfo – Developer adds more properties to ShipInfo class – Add-migration AddedShipInfo (updates existing migration) • Push to database – Update-database -script • Can configure automatic migrations
  • 22. Resources • Code first migrations in team environments – https://msdn.microsoft.com/en-us/data/dn481501.aspx • Configuring/Mapping Properties and Types with the Fluent API – https://msdn.microsoft.com/en-us/data/jj591617.aspx
  • 23. ©2014 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. ©2014 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

  1. 1
  2. Database reverse engineering uses Fluent API & Data Annotations MVC validation understands annotations The precision of a DateTime property The precision and scale of numeric properties A String or Binary property as fixed-length A String property as non-unicode The on-delete behavior of relationships Advanced mapping strategies
  3. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit(AlbumEditViewModel albumViewModel) { //If our ViewModel is valid based on DataAnnotations if (ModelState.IsValid) { //Copy view model to entity var album = new Album() { AlbumArtUrl = albumViewModel.AlbumArtUrl, AlbumId = albumViewModel.AlbumId, ArtistId = albumViewModel.ArtistId, GenreId= albumViewModel.GenreId, //Note lack of price in view model Price= 9.99m, Title = albumViewModel.Title } //Attach it and save it db.Entry(album).State = EntityState.Modified; try { db.SaveChanges(); return RedirectToAction("Index"); } catch (DbEntityValidationException ex) { foreach (var result in ex.EntityValidationErrors) { foreach (var error in result.ValidationErrors) { ModelState.AddModelError(error.PropertyName, error.ErrorMessage); } } return View(album); } } return View(album); } private class AlbumEditViewModel { public int AlbumId { get; set; } public int GenreId { get; set; } public int ArtistId { get; set; } [StringLength(50)] public string Title { get; set; } [StringLength(1024)] public string AlbumArtUrl { get; set; } }
  4. protected override void OnModelCreating(DbModelBuilder modelBuilder) { //Configure domain classes using modelBuilder here base.OnModelCreating(modelBuilder); } Want to specify a foreign key and rename it? (don’t want to rename, don’t use map but then its Artist_ArtistID I believe) modelBuilder.Entity<Album>() .HasRequired<Artist>(s => s.Artist) .WithMany(s => s.Albums) .Map(o=>o.MapKey("ArtistId"));
  5. Install-package entityframework protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.HasDefaultSchema("MusicStore"); modelBuilder.Entity<Album>() .Property(e => e.Title) .HasColumnName("Album_Title"); modelBuilder.Entity<Album>() .HasRequired<Artist>(s => s.Artist) .WithMany(s => s.Albums); }
  6. Open MVC project Add below into context public MusicContext() { Database.SetInitializer(new DropCreateDatabaseAlways<MusicContext>()); } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Album>().ToTable("AlbumInfo", "dbo"); modelBuilder.Entity<Album>().Property(e => e.Title).HasColumnName("Album_Title"); }
  7. Open up connection in Visual Studio Server Manager – Data Connections Right click on db, browse in sql server object explorer Right click on db in SSOE and select Create New Project. Stress this isn’t part of EF Migrations, but one method of managing those scripts. Talk about having to do this anytime your database changes. Do you change DB then script? Do you change SQL, then apply to DB? Now you need either bits and pieces of sql or
  8. Intellisense Enable-migrations – talk about issue if we have Identity installed into an app. http://stackoverflow.com/questions/13469881/how-do-i-enable-ef-migrations-for-multiple-contexts-to-separate-databases Talk about the initial state. The database is created (review of first module) Problem. How do we script this database? Script initial database update-database –script –targetmigration $InitialDatabase Add some fields Add migration Add some fields Add new migration Generate down script: update-database -script -SourceMigration XXXXX –TargetMigration InitialCreate
  9. Enable-Migrations –MigrationsDirectory IdentityMigrations Enable-Migrations –MigrationsDirectory MusicStoreMigrations Add-migration Something -ConfigurationTypeName TriviaMVCPlaya.Migrations.Configuration
  10. Need to specify the full name of the configuration class you are pointing too Enable-Migrations -ContextTypeName TriviaMVCPlaya.Models.ApplicationDbContext Enable-Migrations -ContextTypeName TriviaMVCPlaya.Models.ApplicationDbContext -MigrationsDirectory MigrationsForIdentity add-migration Something -ConfigurationTypeName TriviaMVCPlaya.Migrations.Configuration
  11. Add a decimal Cost field to Album class Add-migration AlbumCost Customize Price = c.Decimal(nullable: false, precision: 18, scale: 2, defaultValue:9.99m),
  12. Point to existing database file. Reverse engineer. Note that this process creates data annotations (to work with validation) AND fluent api. enable-migrations Update-database –Add-Migration Initial –IgnoreChanges script shows nothing (or migrations?) Run app Add a new field, add new migration, update database. We now have migrations table