SlideShare a Scribd company logo
Richie Rump
      @Jorriss
www.jorriss.net
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and Migrations
• Object-Relational Mapping Framework
• Allows developers to retrieve database
  data from an object model.
• Converts object data into relational data
• Uses your classes
• Generates SQL
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and Migrations
• Code First Model
• DbContext
• Fluent API
• Bug Fixes
• Semantic Versioning
Because Entity Framework 4.2 is better
than:
Entity Framework 4.1 Service Pack 2
Update 1 Refresh Release To Web Pack
•   Code First Migrations
•   Data Annotations on non-public properties
•   Additional configuration file settings
•   Removal of EdmMetadata table
•   Bug Fixes
• Added –IgnoreChanges to enable CodeFirst
  against existing database.
• More inevitable bug fixes.
EF 4.3.1 – Bug Fixes

      EF 4.3 - Migrations

      EF 4.2 – Bug Fixes

EF 4.1 - Code First & DbContext


 Entity Framework 4.0
    included with .Net 4.0
Design First                                  Code First

                        Model First                                Code First
                        Create .edmx model in designer             Define classes & mapping in code
       New              Generate DB from .edmx                     Database auto-created at
     Database           Classes auto-generate from                   runtime
                          .edmx


                        Database First                             Code First
                        Reverse engineer .edmx model               Define classes & mapping in code
      Existing          Classes auto-generate from
     Database             .edmx




Adapted from Programming Entity Framework: Code First by Julie Learman and Rowan Miller page 3.
Lovingly stolen from Programming Entity Framework: Code First by Julie Lerman and Rowan Miller page 9.
In a word: Nuget
• What does code look like?
• How do we use it?
• Stop! Demo time.
• Convention over configuration
  – Database naming
  – Primary Key
• SQL Server Express – default database
• dbContext Class
• It’s not enough to use convention.
• Tells EF how to map the object model to the
  database model.
• Place annotations directly against the
  property in your class.
• System.ComponentModel.DataAnnotations
•   Key – Defines a Primary Key
•   Column – Defines DB column name
•   Table – Defines table name for a class
•   Required – Defines a Required DB field
•   NotMapped – Property not in DB mapping
•   MinLength() – Min length for a property
•   MaximumLength() – Max length for property
•   Range() – Defines a valid value range
[Table(“Product_Order")]
public class Order
{
    [Key]
    [Column("Order_ID")]
    public int OrderId { get; set; }
    public DateTime Date { get; set; }
    public OrderState State { get; set; }
    public string Item { get; set; }
    [Range(1, 25)]
    public int Quantity { get; set; }
    [MinLength(3, ErrorMessage="What are you thinking?")]
    [MaxLength(50, ErrorMessage="ERROR!! FAILZ!!!!")]
    public string Name { get; set; }
    [NotMapped]
    public string Note { get; set; }
}
• Allows you to configure EF without polluting
  your classes with annotations.
• Cleaner code
• Can have all EF mapping code in one file.
• Some things you can only do in the Fluent API
Data Annotations
[Column("Order_ID")]
public int Id { get; set; }



Fluent API
modelBuilder.Entity<Order>()
  .Property(p => p.Id).HasColumnName("Order_ID");
• This time it will work…I swear!
• Expressed via the navigation properties in
  your classes
public class Order
{
        public int Id { get; set; }
        public OrderState State { get; set; }
}
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and Migrations
public class Order
 {
    public int Id { get; set; }
    public int OrderStateID { get; set; }
    public OrderState State { get; set; }
 }


public class OrderState
{
   public int Id { get; set; }
}


public OrderConfiguration()
{
    ToTable("Order");
    Property(p => p.OrderStateID).HasColumnName("Order_State_ID");
    HasRequired(p => p.State).WithMany()
      .HasForeignKey(f => f.OrderStateID);
}
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and Migrations
public class Order
 {
    public int Id { get; set; }
    public int PersonID { get; set; }
    public virtual Person SalesPerson { get; set; }
 }

 public class Person
 {
    public int PersonID { get; set; }
    ...
    public List<Order> Orders { get; set; }
 }

public OrderConfiguration()
{
    ToTable("Order");
    Property(p => p.PersonID).HasColumnName("Person_ID");
    HasRequired(p => p.SalesPerson).WithMany(t => t.Orders)
      .HasForeignKey(f => f.PersonID);
}
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and Migrations
public class Order
{
   public int Id { get; set; }
   ...
   public List<Item> Items { get; set; }
}

public class Item
{
   public int Id { get; set; }
   ...
   public List<Order> Orders { get; set; }
}

HasMany(p => p.Items).WithMany(t => t.Orders)
  .Map(m =>
  {
     m.ToTable("Order_Item");
     m.MapLeftKey("Order_ID");
     m.MapRightKey("Item_ID");
  });
• New way to interact with EF objects
• Makes interaction with EF MUCH simpler
• Encapsulates existing EF objects such as
  ObjectContext, ObjectSet and ObjectQuery
• DbContext – Provides facilities querying and
  persisting object changes.
• DbSet – Represents an entity for CRUD
  operations
• Change Tracker API and Validation API are
  other features
EFTestContext context = new EFTestContext();

var query = context.Orders
            .Where(c => c.PersonID == 22)
            .Include(c => c.State)
            .ToList();




List<Order> orders = context.Orders.ToList();
• Easy way to retrieve an object via the Primary
  Key.

EFTestContext context = new EFTestContext();
Person p = context.People.Find(1);
EFTestContext context = new EFTestContext();
Person p = new Person { FirstName = "Testy", LastName = "User" };
context.People.Add(p);
context.SaveChanges();
EFTestContext context = new EFTestContext();
Person p = context.People.Find(1);
context.People.Remove(p);
context.SaveChanges();
• Migrations is a new way to generate database
  changes automatically
• It’s controlled through PowerShell commands
• Can migrate forward or rollback DB changes.
• Migrations can be handled automatically. EF
  will automatically apply change scripts
• To turn Migrations on

PM> Enable-Migrations


• This creates a Migration folder in project
• Creates Configuration.cs file
• Creates __MigrationHistory system table in DB
PM> Add-Migration "Inital" -IgnoreChanges


• “Initial” is the name of the migration
• The –IgnoreChanges switch tells EF to create an
  empty migration. Use this if this is the first
  migration and EF did not create the DB.
• Creates a cs file with the changes since the last
  migration.
• Does not apply changes to DB.
PM> Update-Database


• Pushes the migration changes to the DB
• Use the –script switch to have EF create a SQL
  script of the changes.
• Use –TargetMigration to determine end point for
  DB. (Rollback/Forward)
• Be careful. I wouldn’t run against a production DB.
Y U NO DO DATABASE RIGHT?!?!?!!!
• Now in Release Candidate
• Install using Nuget
    Install-Package EntityFramework –Pre
•   ENUMS!
•   Performance Improvements
•   Spatial Data Types
•   Table-Valued Functions
•   Most features only in .Net 4.5
dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and Migrations
• Julie Lerman’s Blog
      http://thedatafarm.com/blog/
• Rowan Miller’s Blog
      http://romiller.com
• Arthur Vicker’s Blog
      http://blog.oneunicorn.com
• #efhelp on twitter
• StackOverflow (of course)
• PluralSight – Julie Lerman’s EF videos
Richie Rump
@Jorriss
http://jorriss.net
http://dotnetmiami.com

More Related Content

PPTX
Entity Framework: Code First and Magic Unicorns
PPTX
SenchaCon 2016: Modernizing the Ext JS Class System - Don Griffin
PDF
Connect 2016-Move Your XPages Applications to the Fast Lane
PPTX
Entity framework
PDF
Restful App Engine
PDF
How and Where in GLORP
PDF
Requery overview
PPTX
BASTA 2013: Custom OData Provider
Entity Framework: Code First and Magic Unicorns
SenchaCon 2016: Modernizing the Ext JS Class System - Don Griffin
Connect 2016-Move Your XPages Applications to the Fast Lane
Entity framework
Restful App Engine
How and Where in GLORP
Requery overview
BASTA 2013: Custom OData Provider

What's hot (20)

PDF
Squeak DBX
PPTX
Map-Reduce and Apache Hadoop
PPTX
Spring data jpa
PPTX
DSpace 4.2 Transmission: Import/Export
PPTX
Jdbc presentation
PDF
Spring data requery
PDF
Alternatives of JPA/Hibernate
ODP
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...
PPT
5\9 SSIS 2008R2_Training - DataFlow Basics
PDF
Lift Framework
PPTX
Demystifying Oak Search
PPTX
BGOUG 2012 - XML Index Strategies
PPTX
Database connectivity in python
PPT
Xml parsers
PPTX
XFILES, The APEX 4 version - The truth is in there
PPTX
Oak Lucene Indexes
PPT
55 New Features in Java 7
PPTX
Hotsos 2013 - Creating Structure in Unstructured Data
PPTX
Oracle Database 11g Release 2 - XMLDB New Features
Squeak DBX
Map-Reduce and Apache Hadoop
Spring data jpa
DSpace 4.2 Transmission: Import/Export
Jdbc presentation
Spring data requery
Alternatives of JPA/Hibernate
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...
5\9 SSIS 2008R2_Training - DataFlow Basics
Lift Framework
Demystifying Oak Search
BGOUG 2012 - XML Index Strategies
Database connectivity in python
Xml parsers
XFILES, The APEX 4 version - The truth is in there
Oak Lucene Indexes
55 New Features in Java 7
Hotsos 2013 - Creating Structure in Unstructured Data
Oracle Database 11g Release 2 - XMLDB New Features
Ad

Viewers also liked (20)

PDF
SAPCLE Corporate Profile - An Enterprise Application Services Partner of Cho...
PPTX
Menu Pane E Vino
PPTX
Mapa Conceptual Gerencia
PPTX
Apex the peak of good living
PPTX
dotNet Miami - May 17th, 2012: Will Tartak: Designing for Mobile Development
PPTX
Staying connected: An Overview of Announcements from Microsoft’s Connect();
PPTX
 灘校パソコン研究部内lt大会(2012年度)本物
PPTX
Mapa conceptual gerencia
PPT
Menu Pane E Vino
PPTX
dotNet Miami - August 16, 2012 - Windows 8 App Walkthrough
PDF
Guia # 2 karol
PDF
brochure2014
PDF
Guia #8 karol
PDF
Nexus travel
PDF
Denise Sumotzy Art Collection
SAPCLE Corporate Profile - An Enterprise Application Services Partner of Cho...
Menu Pane E Vino
Mapa Conceptual Gerencia
Apex the peak of good living
dotNet Miami - May 17th, 2012: Will Tartak: Designing for Mobile Development
Staying connected: An Overview of Announcements from Microsoft’s Connect();
 灘校パソコン研究部内lt大会(2012年度)本物
Mapa conceptual gerencia
Menu Pane E Vino
dotNet Miami - August 16, 2012 - Windows 8 App Walkthrough
Guia # 2 karol
brochure2014
Guia #8 karol
Nexus travel
Denise Sumotzy Art Collection
Ad

Similar to dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and Migrations (20)

PPTX
Entity Framework: Nakov @ BFU Hackhaton 2015
PPTX
02 beginning code first
PPTX
02 beginning code first
PPTX
Real World MVC
PPTX
Webinar: What's new in the .NET Driver
PDF
ITB 2023 qb, Migration, Seeders. Recipe For Success - Gavin-Pickin.pdf
PDF
Access Data from XPages with the Relational Controls
PPTX
PPTX
Entity Framework Database and Code First
PPTX
05 entity framework
PDF
Data Migrations in the App Engine Datastore
PDF
Intake 37 ef2
PDF
9 Python programming notes for ktu physics and computer application semester 4
PPT
What's New for Data?
PPTX
Jdbc Java Programming
PPT
Entity framework 4.0
PDF
JavaScript - Chapter 12 - Document Object Model
PPTX
Ef code first
PPTX
jdbcppt.pptx , jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt
PPTX
jdbcppt.pptx , jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt
Entity Framework: Nakov @ BFU Hackhaton 2015
02 beginning code first
02 beginning code first
Real World MVC
Webinar: What's new in the .NET Driver
ITB 2023 qb, Migration, Seeders. Recipe For Success - Gavin-Pickin.pdf
Access Data from XPages with the Relational Controls
Entity Framework Database and Code First
05 entity framework
Data Migrations in the App Engine Datastore
Intake 37 ef2
9 Python programming notes for ktu physics and computer application semester 4
What's New for Data?
Jdbc Java Programming
Entity framework 4.0
JavaScript - Chapter 12 - Document Object Model
Ef code first
jdbcppt.pptx , jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt
jdbcppt.pptx , jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt

Recently uploaded (20)

PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Electronic commerce courselecture one. Pdf
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
Spectroscopy.pptx food analysis technology
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
KodekX | Application Modernization Development
PDF
Approach and Philosophy of On baking technology
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
NewMind AI Weekly Chronicles - August'25 Week I
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Per capita expenditure prediction using model stacking based on satellite ima...
Electronic commerce courselecture one. Pdf
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Spectral efficient network and resource selection model in 5G networks
Dropbox Q2 2025 Financial Results & Investor Presentation
Advanced methodologies resolving dimensionality complications for autism neur...
Spectroscopy.pptx food analysis technology
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Digital-Transformation-Roadmap-for-Companies.pptx
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
sap open course for s4hana steps from ECC to s4
Building Integrated photovoltaic BIPV_UPV.pdf
Programs and apps: productivity, graphics, security and other tools
KodekX | Application Modernization Development
Approach and Philosophy of On baking technology
“AI and Expert System Decision Support & Business Intelligence Systems”
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...

dotNet Miami - June 21, 2012: Richie Rump: Entity Framework: Code First and Migrations

  • 1. Richie Rump @Jorriss www.jorriss.net
  • 3. • Object-Relational Mapping Framework • Allows developers to retrieve database data from an object model. • Converts object data into relational data • Uses your classes • Generates SQL
  • 5. • Code First Model • DbContext • Fluent API
  • 6. • Bug Fixes • Semantic Versioning Because Entity Framework 4.2 is better than: Entity Framework 4.1 Service Pack 2 Update 1 Refresh Release To Web Pack
  • 7. Code First Migrations • Data Annotations on non-public properties • Additional configuration file settings • Removal of EdmMetadata table • Bug Fixes
  • 8. • Added –IgnoreChanges to enable CodeFirst against existing database. • More inevitable bug fixes.
  • 9. EF 4.3.1 – Bug Fixes EF 4.3 - Migrations EF 4.2 – Bug Fixes EF 4.1 - Code First & DbContext Entity Framework 4.0 included with .Net 4.0
  • 10. Design First Code First Model First Code First Create .edmx model in designer Define classes & mapping in code New Generate DB from .edmx Database auto-created at Database Classes auto-generate from runtime .edmx Database First Code First Reverse engineer .edmx model Define classes & mapping in code Existing Classes auto-generate from Database .edmx Adapted from Programming Entity Framework: Code First by Julie Learman and Rowan Miller page 3.
  • 11. Lovingly stolen from Programming Entity Framework: Code First by Julie Lerman and Rowan Miller page 9.
  • 12. In a word: Nuget
  • 13. • What does code look like? • How do we use it? • Stop! Demo time.
  • 14. • Convention over configuration – Database naming – Primary Key • SQL Server Express – default database • dbContext Class
  • 15. • It’s not enough to use convention. • Tells EF how to map the object model to the database model. • Place annotations directly against the property in your class. • System.ComponentModel.DataAnnotations
  • 16. Key – Defines a Primary Key • Column – Defines DB column name • Table – Defines table name for a class • Required – Defines a Required DB field • NotMapped – Property not in DB mapping • MinLength() – Min length for a property • MaximumLength() – Max length for property • Range() – Defines a valid value range
  • 17. [Table(“Product_Order")] public class Order { [Key] [Column("Order_ID")] public int OrderId { get; set; } public DateTime Date { get; set; } public OrderState State { get; set; } public string Item { get; set; } [Range(1, 25)] public int Quantity { get; set; } [MinLength(3, ErrorMessage="What are you thinking?")] [MaxLength(50, ErrorMessage="ERROR!! FAILZ!!!!")] public string Name { get; set; } [NotMapped] public string Note { get; set; } }
  • 18. • Allows you to configure EF without polluting your classes with annotations. • Cleaner code • Can have all EF mapping code in one file. • Some things you can only do in the Fluent API
  • 19. Data Annotations [Column("Order_ID")] public int Id { get; set; } Fluent API modelBuilder.Entity<Order>() .Property(p => p.Id).HasColumnName("Order_ID");
  • 20. • This time it will work…I swear!
  • 21. • Expressed via the navigation properties in your classes public class Order { public int Id { get; set; } public OrderState State { get; set; } }
  • 23. public class Order { public int Id { get; set; } public int OrderStateID { get; set; } public OrderState State { get; set; } } public class OrderState { public int Id { get; set; } } public OrderConfiguration() { ToTable("Order"); Property(p => p.OrderStateID).HasColumnName("Order_State_ID"); HasRequired(p => p.State).WithMany() .HasForeignKey(f => f.OrderStateID); }
  • 25. public class Order { public int Id { get; set; } public int PersonID { get; set; } public virtual Person SalesPerson { get; set; } } public class Person { public int PersonID { get; set; } ... public List<Order> Orders { get; set; } } public OrderConfiguration() { ToTable("Order"); Property(p => p.PersonID).HasColumnName("Person_ID"); HasRequired(p => p.SalesPerson).WithMany(t => t.Orders) .HasForeignKey(f => f.PersonID); }
  • 27. public class Order { public int Id { get; set; } ... public List<Item> Items { get; set; } } public class Item { public int Id { get; set; } ... public List<Order> Orders { get; set; } } HasMany(p => p.Items).WithMany(t => t.Orders) .Map(m => { m.ToTable("Order_Item"); m.MapLeftKey("Order_ID"); m.MapRightKey("Item_ID"); });
  • 28. • New way to interact with EF objects • Makes interaction with EF MUCH simpler • Encapsulates existing EF objects such as ObjectContext, ObjectSet and ObjectQuery
  • 29. • DbContext – Provides facilities querying and persisting object changes. • DbSet – Represents an entity for CRUD operations • Change Tracker API and Validation API are other features
  • 30. EFTestContext context = new EFTestContext(); var query = context.Orders .Where(c => c.PersonID == 22) .Include(c => c.State) .ToList(); List<Order> orders = context.Orders.ToList();
  • 31. • Easy way to retrieve an object via the Primary Key. EFTestContext context = new EFTestContext(); Person p = context.People.Find(1);
  • 32. EFTestContext context = new EFTestContext(); Person p = new Person { FirstName = "Testy", LastName = "User" }; context.People.Add(p); context.SaveChanges();
  • 33. EFTestContext context = new EFTestContext(); Person p = context.People.Find(1); context.People.Remove(p); context.SaveChanges();
  • 34. • Migrations is a new way to generate database changes automatically • It’s controlled through PowerShell commands • Can migrate forward or rollback DB changes. • Migrations can be handled automatically. EF will automatically apply change scripts
  • 35. • To turn Migrations on PM> Enable-Migrations • This creates a Migration folder in project • Creates Configuration.cs file • Creates __MigrationHistory system table in DB
  • 36. PM> Add-Migration "Inital" -IgnoreChanges • “Initial” is the name of the migration • The –IgnoreChanges switch tells EF to create an empty migration. Use this if this is the first migration and EF did not create the DB. • Creates a cs file with the changes since the last migration. • Does not apply changes to DB.
  • 37. PM> Update-Database • Pushes the migration changes to the DB • Use the –script switch to have EF create a SQL script of the changes. • Use –TargetMigration to determine end point for DB. (Rollback/Forward) • Be careful. I wouldn’t run against a production DB.
  • 38. Y U NO DO DATABASE RIGHT?!?!?!!!
  • 39. • Now in Release Candidate • Install using Nuget Install-Package EntityFramework –Pre • ENUMS! • Performance Improvements • Spatial Data Types • Table-Valued Functions • Most features only in .Net 4.5
  • 41. • Julie Lerman’s Blog http://thedatafarm.com/blog/ • Rowan Miller’s Blog http://romiller.com • Arthur Vicker’s Blog http://blog.oneunicorn.com • #efhelp on twitter • StackOverflow (of course) • PluralSight – Julie Lerman’s EF videos

Editor's Notes

  • #5: EDMX. Entity Data Model. A representation of your classes in XML. Three files: Conceptual (Entity Model) CDSL. Logical (Database Model) SSDL Mapping (Between Entity and Database) MSL. EDMX -&gt; In memory model and metadata. EF translates the XML into an memory model. It uses this model to persist and read data from the database.