SlideShare una empresa de Scribd logo
1 de 42
Richie Rump
      @Jorriss
www.jorriss.net
• 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
• 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; }
}
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);
}
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);
}
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 beta
• Install using Nuget
    Install-Package EntityFramework –Pre
•   ENUMS!
•   Performance Improvements
•   Spatial Data Types
•   Table-Valued Functions
•   Most features only in .Net 4.5
• 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)
• PluralSite – Julie Lerman’s EF videos
Richie Rump
@Jorriss
http://jorriss.net
http://dotnetmiami.com

Más contenido relacionado

La actualidad más candente

Entity Framework
Entity FrameworkEntity Framework
Entity Frameworkvrluckyin
 
Entity Framework Overview
Entity Framework OverviewEntity Framework Overview
Entity Framework OverviewEric Nelson
 
Entity framework and how to use it
Entity framework and how to use itEntity framework and how to use it
Entity framework and how to use itnspyre_net
 
Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015Svetlin Nakov
 
Introducing the Entity Framework
Introducing the Entity FrameworkIntroducing the Entity Framework
Introducing the Entity FrameworkLearnNowOnline
 
Entity framework 6
Entity framework 6Entity framework 6
Entity framework 6Ken Tucker
 
Entity Framework v2 Best Practices
Entity Framework v2 Best PracticesEntity Framework v2 Best Practices
Entity Framework v2 Best PracticesAndri Yadi
 
Building nTier Applications with Entity Framework Services
Building nTier Applications with Entity Framework ServicesBuilding nTier Applications with Entity Framework Services
Building nTier Applications with Entity Framework ServicesDavid McCarter
 
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
 
Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)David McCarter
 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core DataMake School
 
Spring Data - Intro (Odessa Java TechTalks)
Spring Data - Intro (Odessa Java TechTalks)Spring Data - Intro (Odessa Java TechTalks)
Spring Data - Intro (Odessa Java TechTalks)Igor Anishchenko
 
Entity Framework v1 and v2
Entity Framework v1 and v2Entity Framework v1 and v2
Entity Framework v1 and v2Eric Nelson
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate pptAneega
 
Microsoft Entity Framework
Microsoft Entity FrameworkMicrosoft Entity Framework
Microsoft Entity FrameworkMahmoud Tolba
 
Lerman Vvs14 Ef Tips And Tricks
Lerman Vvs14  Ef Tips And TricksLerman Vvs14  Ef Tips And Tricks
Lerman Vvs14 Ef Tips And TricksJulie Lerman
 

La actualidad más candente (20)

Entity Framework
Entity FrameworkEntity Framework
Entity Framework
 
Entity Framework Overview
Entity Framework OverviewEntity Framework Overview
Entity Framework Overview
 
Entity Framework 4
Entity Framework 4Entity Framework 4
Entity Framework 4
 
Entity framework and how to use it
Entity framework and how to use itEntity framework and how to use it
Entity framework and how to use it
 
Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015
 
Introducing the Entity Framework
Introducing the Entity FrameworkIntroducing the Entity Framework
Introducing the Entity Framework
 
Entity framework 6
Entity framework 6Entity framework 6
Entity framework 6
 
Entity Framework v2 Best Practices
Entity Framework v2 Best PracticesEntity Framework v2 Best Practices
Entity Framework v2 Best Practices
 
Building nTier Applications with Entity Framework Services
Building nTier Applications with Entity Framework ServicesBuilding nTier Applications with Entity Framework Services
Building nTier Applications with Entity Framework Services
 
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...
 
Introduction to Hibernate
Introduction to HibernateIntroduction to Hibernate
Introduction to Hibernate
 
Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)
 
Linq
LinqLinq
Linq
 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core Data
 
Spring Data - Intro (Odessa Java TechTalks)
Spring Data - Intro (Odessa Java TechTalks)Spring Data - Intro (Odessa Java TechTalks)
Spring Data - Intro (Odessa Java TechTalks)
 
Entity Framework v1 and v2
Entity Framework v1 and v2Entity Framework v1 and v2
Entity Framework v1 and v2
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
 
Microsoft Entity Framework
Microsoft Entity FrameworkMicrosoft Entity Framework
Microsoft Entity Framework
 
Lerman Vvs14 Ef Tips And Tricks
Lerman Vvs14  Ef Tips And TricksLerman Vvs14  Ef Tips And Tricks
Lerman Vvs14 Ef Tips And Tricks
 
ASP.NET 09 - ADO.NET
ASP.NET 09 - ADO.NETASP.NET 09 - ADO.NET
ASP.NET 09 - ADO.NET
 

Destacado

Entity Framework 6 for developers, Code-First!
Entity Framework 6 for developers, Code-First!Entity Framework 6 for developers, Code-First!
Entity Framework 6 for developers, Code-First!Michael Denny
 
Entity Framework Core & Micro-Orms with Asp.Net Core
Entity Framework Core & Micro-Orms with Asp.Net CoreEntity Framework Core & Micro-Orms with Asp.Net Core
Entity Framework Core & Micro-Orms with Asp.Net CoreStephane Belkheraz
 
Feedback Loops...to infinity, and beyond!
Feedback Loops...to infinity, and beyond!Feedback Loops...to infinity, and beyond!
Feedback Loops...to infinity, and beyond!Rui Carvalho
 
Getting started with entity framework 6 code first using mvc 5
Getting started with entity framework 6 code first using mvc 5Getting started with entity framework 6 code first using mvc 5
Getting started with entity framework 6 code first using mvc 5Ehtsham Khan
 
ADO.NET Entity Framework
ADO.NET Entity FrameworkADO.NET Entity Framework
ADO.NET Entity Frameworkukdpe
 
MVC 6 - Tag Helpers and View Components
MVC 6 - Tag Helpers and View ComponentsMVC 6 - Tag Helpers and View Components
MVC 6 - Tag Helpers and View ComponentsDavid Paquette
 
Improve your web dev workflow in Visual Studio
Improve your web dev workflow in Visual StudioImprove your web dev workflow in Visual Studio
Improve your web dev workflow in Visual StudioDavid Paquette
 
04 - [ASP.NET Core] Entity Framework Core
04 - [ASP.NET Core] Entity Framework Core 04 - [ASP.NET Core] Entity Framework Core
04 - [ASP.NET Core] Entity Framework Core Cellenza
 
Repository and Unit Of Work Design Patterns
Repository and Unit Of Work Design PatternsRepository and Unit Of Work Design Patterns
Repository and Unit Of Work Design PatternsHatim Hakeel
 
State of entity framework
State of entity frameworkState of entity framework
State of entity frameworkDavid Paquette
 
ORM технологии в .NET (Nhibernate, Linq To SQL, Entity Framework)
ORM технологии в .NET (Nhibernate, Linq To SQL, Entity Framework)ORM технологии в .NET (Nhibernate, Linq To SQL, Entity Framework)
ORM технологии в .NET (Nhibernate, Linq To SQL, Entity Framework)Pavel Tsukanov
 

Destacado (14)

Entity Framework 6 for developers, Code-First!
Entity Framework 6 for developers, Code-First!Entity Framework 6 for developers, Code-First!
Entity Framework 6 for developers, Code-First!
 
Entity Framework Core & Micro-Orms with Asp.Net Core
Entity Framework Core & Micro-Orms with Asp.Net CoreEntity Framework Core & Micro-Orms with Asp.Net Core
Entity Framework Core & Micro-Orms with Asp.Net Core
 
Feedback Loops...to infinity, and beyond!
Feedback Loops...to infinity, and beyond!Feedback Loops...to infinity, and beyond!
Feedback Loops...to infinity, and beyond!
 
Getting started with entity framework 6 code first using mvc 5
Getting started with entity framework 6 code first using mvc 5Getting started with entity framework 6 code first using mvc 5
Getting started with entity framework 6 code first using mvc 5
 
ADO.NET Entity Framework
ADO.NET Entity FrameworkADO.NET Entity Framework
ADO.NET Entity Framework
 
MVC 6 - Tag Helpers and View Components
MVC 6 - Tag Helpers and View ComponentsMVC 6 - Tag Helpers and View Components
MVC 6 - Tag Helpers and View Components
 
Improve your web dev workflow in Visual Studio
Improve your web dev workflow in Visual StudioImprove your web dev workflow in Visual Studio
Improve your web dev workflow in Visual Studio
 
04 - [ASP.NET Core] Entity Framework Core
04 - [ASP.NET Core] Entity Framework Core 04 - [ASP.NET Core] Entity Framework Core
04 - [ASP.NET Core] Entity Framework Core
 
Repository and Unit Of Work Design Patterns
Repository and Unit Of Work Design PatternsRepository and Unit Of Work Design Patterns
Repository and Unit Of Work Design Patterns
 
Orms vs Micro-ORMs
Orms vs Micro-ORMsOrms vs Micro-ORMs
Orms vs Micro-ORMs
 
State of entity framework
State of entity frameworkState of entity framework
State of entity framework
 
ORM технологии в .NET (Nhibernate, Linq To SQL, Entity Framework)
ORM технологии в .NET (Nhibernate, Linq To SQL, Entity Framework)ORM технологии в .NET (Nhibernate, Linq To SQL, Entity Framework)
ORM технологии в .NET (Nhibernate, Linq To SQL, Entity Framework)
 
Intake 37 ef1
Intake 37 ef1Intake 37 ef1
Intake 37 ef1
 
Intake 37 ef2
Intake 37 ef2Intake 37 ef2
Intake 37 ef2
 

Similar a Entity Framework: Code First and Magic Unicorns

02 beginning code first
02   beginning code first02   beginning code first
02 beginning code firstMaxim Shaptala
 
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
 
Access Data from XPages with the Relational Controls
Access Data from XPages with the Relational ControlsAccess Data from XPages with the Relational Controls
Access Data from XPages with the Relational ControlsTeamstudio
 
05 entity framework
05 entity framework05 entity framework
05 entity frameworkglubox
 
Data Migrations in the App Engine Datastore
Data Migrations in the App Engine DatastoreData Migrations in the App Engine Datastore
Data Migrations in the App Engine DatastoreRyan Morlok
 
What's New for Data?
What's New for Data?What's New for Data?
What's New for Data?ukdpe
 
Jdbc Java Programming
Jdbc Java ProgrammingJdbc Java Programming
Jdbc Java Programmingchhaichivon
 
Entity framework 4.0
Entity framework 4.0Entity framework 4.0
Entity framework 4.0Abhishek Sur
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object ModelWebStackAcademy
 
Lerman Adx303 Entity Framework 4 In Aspnet
Lerman Adx303 Entity Framework 4 In AspnetLerman Adx303 Entity Framework 4 In Aspnet
Lerman Adx303 Entity Framework 4 In AspnetJulie Lerman
 
Modern, Scalable, Ambitious apps with Ember.js
Modern, Scalable, Ambitious apps with Ember.jsModern, Scalable, Ambitious apps with Ember.js
Modern, Scalable, Ambitious apps with Ember.jsMike North
 
Generating Code with Oracle SQL Developer Data Modeler
Generating Code with Oracle SQL Developer Data ModelerGenerating Code with Oracle SQL Developer Data Modeler
Generating Code with Oracle SQL Developer Data ModelerRob van den Berg
 
MVC and Entity Framework 4
MVC and Entity Framework 4MVC and Entity Framework 4
MVC and Entity Framework 4James Johnson
 
Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)David McCarter
 

Similar a Entity Framework: Code First and Magic Unicorns (20)

02 beginning code first
02   beginning code first02   beginning code first
02 beginning code first
 
02 beginning code first
02   beginning code first02   beginning code first
02 beginning code first
 
Real World MVC
Real World MVCReal World MVC
Real World MVC
 
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
 
Access Data from XPages with the Relational Controls
Access Data from XPages with the Relational ControlsAccess Data from XPages with the Relational Controls
Access Data from XPages with the Relational Controls
 
La sql
La sqlLa sql
La sql
 
05 entity framework
05 entity framework05 entity framework
05 entity framework
 
Data Migrations in the App Engine Datastore
Data Migrations in the App Engine DatastoreData Migrations in the App Engine Datastore
Data Migrations in the App Engine Datastore
 
What's New for Data?
What's New for Data?What's New for Data?
What's New for Data?
 
Jdbc Java Programming
Jdbc Java ProgrammingJdbc Java Programming
Jdbc Java Programming
 
Entity framework 4.0
Entity framework 4.0Entity framework 4.0
Entity framework 4.0
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
 
05 entity framework
05 entity framework05 entity framework
05 entity framework
 
Lerman Adx303 Entity Framework 4 In Aspnet
Lerman Adx303 Entity Framework 4 In AspnetLerman Adx303 Entity Framework 4 In Aspnet
Lerman Adx303 Entity Framework 4 In Aspnet
 
Modern, Scalable, Ambitious apps with Ember.js
Modern, Scalable, Ambitious apps with Ember.jsModern, Scalable, Ambitious apps with Ember.js
Modern, Scalable, Ambitious apps with Ember.js
 
Generating Code with Oracle SQL Developer Data Modeler
Generating Code with Oracle SQL Developer Data ModelerGenerating Code with Oracle SQL Developer Data Modeler
Generating Code with Oracle SQL Developer Data Modeler
 
Jsp project module
Jsp project moduleJsp project module
Jsp project module
 
MVC and Entity Framework 4
MVC and Entity Framework 4MVC and Entity Framework 4
MVC and Entity Framework 4
 
Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)Building nTier Applications with Entity Framework Services (Part 1)
Building nTier Applications with Entity Framework Services (Part 1)
 
Linq
LinqLinq
Linq
 

Último

Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 

Último (20)

Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 

Entity Framework: Code First and Magic Unicorns

  • 1. Richie Rump @Jorriss www.jorriss.net
  • 2.
  • 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
  • 4.
  • 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; } }
  • 22.
  • 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); }
  • 24.
  • 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); }
  • 26.
  • 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 beta • Install using Nuget Install-Package EntityFramework –Pre • ENUMS! • Performance Improvements • Spatial Data Types • Table-Valued Functions • Most features only in .Net 4.5
  • 40.
  • 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) • PluralSite – Julie Lerman’s EF videos

Notas del editor

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