04 managing the database

23
Click to edit Master subtitle style 04 | Managing the Database Adam Tuliper | Technical Evangelist, Microsoft Christopher Harrison | Content Developer, Microsoft

Upload: -

Post on 17-Feb-2017

1.661 views

Category:

Education


0 download

TRANSCRIPT

Page 1: 04   managing the database

Click to edit Master subtitle style

04 | Managing the Database

Adam Tuliper | Technical Evangelist, MicrosoftChristopher Harrison | Content Developer, Microsoft

Page 2: 04   managing the database

Module Overview• Fluent API• Code First Migrations

Page 3: 04   managing the database

Click to edit Master subtitle style

Fluent API

Page 4: 04   managing the database

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);

Page 5: 04   managing the database

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

Page 6: 04   managing the database

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

Page 7: 04   managing the database

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

Page 8: 04   managing the database

OnModelCreating• Override OnModelCreating in DbContextprotected 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);}

Page 9: 04   managing the database

DEMODEMOFluent API Basics

Page 10: 04   managing the database

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

Page 11: 04   managing the database

DEMODEMOFluent API Remapping tables and columns

Page 12: 04   managing the database

Click to edit Master subtitle style

Code First Migrations

Page 13: 04   managing the database

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

Page 14: 04   managing the database

DEMODEMOManual Script Management

Page 15: 04   managing the database

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)

Page 16: 04   managing the database

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

Page 17: 04   managing the database

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

Page 18: 04   managing the database

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

Page 19: 04   managing the database

DEMODEMOSetting up migrations

Page 20: 04   managing the database

DEMODEMOCustomizing Migrations

Page 21: 04   managing the database

DEMODEMOManaging an existing database

Page 22: 04   managing the 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

Page 23: 04   managing the database

©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.