42
Entity Framework Code First and Migrations Richie Rump @Jorriss www.jorriss.net

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

Embed Size (px)

DESCRIPTION

dotNet Miami - June 21, 2012: Presented by Richie Rump: Traditionally, Entity Framework has used a designer and XML files to define the conceptual and storage models. Now with Entity Framework Code First we can ditch the XML files and define the data model directly in code. This session will give an overview of all of the awesomeness that is Code First including Data Annotations, Fluent API, DbContext and the new Migrations feature. Be prepared for a fast moving and interactive session filled with great information on how to access your data.

Citation preview

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

Entity Framework Code First and Migrations

Richie Rump@Jorriss

www.jorriss.net

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

Who is this dude?

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

What is Entity Framework?

• 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

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

Before Code First…

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

EF 4.1 – A New Hope

• Code First Model• DbContext• Fluent API

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

EF 4.2 – Much Ado About Versioning

• Bug Fixes• Semantic VersioningBecause Entity Framework 4.2 is better than:Entity Framework 4.1 Service Pack 2 Update 1 Refresh Release To Web Pack

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

EF 4.3 – More Like Hibernate

• Code First Migrations• Data Annotations on non-public properties• Additional configuration file settings• Removal of EdmMetadata table• Bug Fixes

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

EF 4.3.1 – Oops, I Did It Again

• Added –IgnoreChanges to enable CodeFirst against existing database.

• More inevitable bug fixes.

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

How it all fits

Entity Framework 4.0included with .Net 4.0

EF 4.1 - Code First & DbContext

EF 4.2 – Bug Fixes

EF 4.3 - Migrations

EF 4.3.1 – Bug Fixes

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

Entity Framework ModelsDesign First Code First

New Database

Existing Database

Model FirstCreate .edmx model in designerGenerate DB from .edmxClasses auto-generate from .edmx

Database FirstReverse engineer .edmx modelClasses auto-generate from .edmx

Code FirstDefine classes & mapping in codeDatabase auto-created at runtime

Code FirstDefine classes & mapping in code

Adapted from Programming Entity Framework: Code First by Julie Learman and Rowan Miller page 3.

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

So how does this thing work?

Lovingly stolen from Programming Entity Framework: Code First by Julie Lerman and Rowan Miller page 9.

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

How do I get this thing?

In a word: Nuget

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

Code First

• What does code look like?• How do we use it?• Stop! Demo time.

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

Review

• Convention over configuration– Database naming– Primary Key

• SQL Server Express – default database• dbContext Class

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

Data Annotations

• 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

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

Common Data Annotations

• 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

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

Data Annotation - Example    [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; }    }

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

Fluent API

• 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

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

A Comparison

Data Annotations

Fluent APImodelBuilder.Entity<Order>() .Property(p => p.Id).HasColumnName("Order_ID");

[Column("Order_ID")]public int Id { get; set; }

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

Demo – Fluent API

• This time it will work…I swear!

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

Relationships: Everyone wants one

• Expressed via the navigation properties in your classes

public class Order    

{

        public int Id { get; set; }

       public OrderState State { get; set; }

}

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

Fluent API: M:1

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

Fluent API: M:1

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 OrderStateID { get; set; } public OrderState State { get; set; } }

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

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

Fluent API: M:1 with Navigation

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

Fluent API: M:1 with Navigation

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 Person { public int PersonID { get; set; } ... public List<Order> Orders { get; set; } }

public class Order { public int Id { get; set; } public int PersonID { get; set; } public virtual Person SalesPerson { get; set; } }

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

Fluent API: M:N

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

Fluent API: M:N

HasMany(p => p.Items).WithMany(t => t.Orders) .Map(m =>   { m.ToTable("Order_Item"); m.MapLeftKey("Order_ID"); m.MapRightKey("Item_ID"); });

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

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

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

DbContext API

• New way to interact with EF objects• Makes interaction with EF MUCH simpler• Encapsulates existing EF objects such as

ObjectContext, ObjectSet and ObjectQuery

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

DbContext API

• DbContext – Provides facilities querying and persisting object changes.

• DbSet – Represents an entity for CRUD operations

• Change Tracker API and Validation API are other features

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

Query Examples

EFTestContext context = new EFTestContext();

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

List<Order> orders = context.Orders.ToList();

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

DbContext API

• Easy way to retrieve an object via the Primary Key.

EFTestContext context = new EFTestContext(); Person p = context.People.Find(1);

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

Add Object

EFTestContext context = new EFTestContext(); Person p = new Person { FirstName = "Testy", LastName = "User" }; context.People.Add(p); context.SaveChanges();

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

Delete Object

EFTestContext context = new EFTestContext(); Person p = context.People.Find(1); context.People.Remove(p); context.SaveChanges();

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

Migrations

• 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

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

Enable Migrations

• To turn Migrations on

• This creates a Migration folder in project• Creates Configuration.cs file• Creates __MigrationHistory system table in DB

PM> Enable-Migrations

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

Add Migration

• “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> Add-Migration "Inital" -IgnoreChanges

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

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.

PM> Update-Database

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

Y U NO DO DATABASE RIGHT?!?!?!!!

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

What’s Next? EF 5.0

• 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

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

Reference

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

Other References

• Julie Lerman’s Bloghttp://thedatafarm.com/blog/

• Rowan Miller’s Bloghttp://romiller.com

• Arthur Vicker’s Bloghttp://blog.oneunicorn.com

• #efhelp on twitter• StackOverflow (of course)• PluralSight – Julie Lerman’s EF videos

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

Thank You!!

Richie Rump@Jorrisshttp://jorriss.nethttp://dotnetmiami.com