04 managing the database

Preview:

Citation preview

Click to edit Master subtitle style

04 | Managing the Database

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

Module Overview• Fluent API• Code First Migrations

Click to edit Master subtitle style

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

DEMODEMOFluent 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

DEMODEMOFluent API Remapping tables and columns

Click to edit Master subtitle style

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

DEMODEMOManual 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

DEMODEMOSetting up migrations

DEMODEMOCustomizing Migrations

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

Recommended