Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

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

1,302 views

Published on

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.

Published in: Technology, Education
  • Be the first to comment

  • Be the first to like this

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

  1. 1. Richie Rump @Jorrisswww.jorriss.net
  2. 2. • 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
  3. 3. • Code First Model• DbContext• Fluent API
  4. 4. • Bug Fixes• Semantic VersioningBecause Entity Framework 4.2 is betterthan:Entity Framework 4.1 Service Pack 2Update 1 Refresh Release To Web Pack
  5. 5. • Code First Migrations• Data Annotations on non-public properties• Additional configuration file settings• Removal of EdmMetadata table• Bug Fixes
  6. 6. • Added –IgnoreChanges to enable CodeFirst against existing database.• More inevitable bug fixes.
  7. 7. EF 4.3.1 – Bug Fixes EF 4.3 - Migrations EF 4.2 – Bug FixesEF 4.1 - Code First & DbContext Entity Framework 4.0 included with .Net 4.0
  8. 8. 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 .edmxAdapted from Programming Entity Framework: Code First by Julie Learman and Rowan Miller page 3.
  9. 9. Lovingly stolen from Programming Entity Framework: Code First by Julie Lerman and Rowan Miller page 9.
  10. 10. In a word: Nuget
  11. 11. • What does code look like?• How do we use it?• Stop! Demo time.
  12. 12. • Convention over configuration – Database naming – Primary Key• SQL Server Express – default database• dbContext Class
  13. 13. • 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
  14. 14. • 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
  15. 15. [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; }}
  16. 16. • 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
  17. 17. Data Annotations[Column("Order_ID")]public int Id { get; set; }Fluent APImodelBuilder.Entity<Order>() .Property(p => p.Id).HasColumnName("Order_ID");
  18. 18. • This time it will work…I swear!
  19. 19. • Expressed via the navigation properties in your classespublic class Order{ public int Id { get; set; } public OrderState State { get; set; }}
  20. 20. 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);}
  21. 21. 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);}
  22. 22. 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"); });
  23. 23. • New way to interact with EF objects• Makes interaction with EF MUCH simpler• Encapsulates existing EF objects such as ObjectContext, ObjectSet and ObjectQuery
  24. 24. • DbContext – Provides facilities querying and persisting object changes.• DbSet – Represents an entity for CRUD operations• Change Tracker API and Validation API are other features
  25. 25. EFTestContext context = new EFTestContext();var query = context.Orders .Where(c => c.PersonID == 22) .Include(c => c.State) .ToList();List<Order> orders = context.Orders.ToList();
  26. 26. • Easy way to retrieve an object via the Primary Key.EFTestContext context = new EFTestContext();Person p = context.People.Find(1);
  27. 27. EFTestContext context = new EFTestContext();Person p = new Person { FirstName = "Testy", LastName = "User" };context.People.Add(p);context.SaveChanges();
  28. 28. EFTestContext context = new EFTestContext();Person p = context.People.Find(1);context.People.Remove(p);context.SaveChanges();
  29. 29. • 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
  30. 30. • To turn Migrations onPM> Enable-Migrations• This creates a Migration folder in project• Creates Configuration.cs file• Creates __MigrationHistory system table in DB
  31. 31. 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.
  32. 32. 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.
  33. 33. Y U NO DO DATABASE RIGHT?!?!?!!!
  34. 34. • 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
  35. 35. • 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
  36. 36. Richie Rump@Jorrisshttp://jorriss.nethttp://dotnetmiami.com

×