1 / 43

( How to) Put your Code First with Entity Framework

( How to) Put your Code First with Entity Framework. Max Weber – Architect. We thank the following companies for their gracious sponsorship. Platinum Sponsor. Gold Sponsors. Silver Sponsors. Distribution of slide deck. This slide deck will be made available from the following locations:

lajos
Télécharger la présentation

( How to) Put your Code First with Entity Framework

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. (How to) Put your Code First with Entity Framework Max Weber – Architect

  2. We thank the following companies for their gracious sponsorship Platinum Sponsor Gold Sponsors Silver Sponsors

  3. Distribution of slide deck • This slide deck will be made available from the following locations: • Tallan blogs - blogs.tallan.com • Code Camp NYC - nyc.codecamp.us

  4. Our Agenda • Brief introduction to Entity Framework (EF) • Intro to EF Code First • Talking about, then coding: • Entities and Associations • Adding Metadata / annotations • Validation • Database Initializers / seeding / testing • Inheritance Mapping • Drawbacks • Summary

  5. What is Entity Framework? (Abridged) • Based on the Entity Data Model (EDM) • EDM borrows from Entity-Relationship Model • Current version is v4.0 (Shipped with VS2010)

  6. Entity Framework set up shop where?

  7. What is the Entity Data Model? • Entity Data Model • The Entity Data Model (EDM) is a set of concepts that describe the structure of data, regardless of its stored form. The EDM borrows from the Entity-Relationship Model described by Peter Chen in 1976, but it also builds on the Entity-Relationship Model and extends its traditional uses. • Extensions to E-R Model: • Separation of the entities and relationships from their storage medium • http://msdn.microsoft.com/en-us/library/ee382825.aspx

  8. Entity Framework’s supply chain

  9. Data Providers – Entity Framework 4 • EF uses the ADO.NET Data Provider model • Providers • MS SQL Server • Indirect access to other DBs using ODBC, OLEDB • VistaDB • Devart • OpenLink Software • Synergy • …5+ more • ADO.NET Data Providers List • http://msdn.microsoft.com/en-us/data/dd363565.aspx

  10. EF: What comes first? • Database First • Create model from database • Designer / XML files • Model First • Create database from model • Designer / XML files • Code First • Create database from model • Code-only interface • Available exclusively in “Magic Unicorn” Edition

  11. Magic Unicorns? Seriously? • Based on Entity Framework “Magic Unicorn Edition” (Thanks Scott Hanselman) • CTP5 – minimal breaking changes left • Next version: RTW (Q1 2011) • Version is basically, EF4 SP1 or EF5 • Code interface instead of XML to EF

  12. How do I land myself a Magical Unicorn? • NuGet Package Manager (VS 2010) (recommended) • Download extension then install package “EFCodeFirst” • Download from MSDN • Link here. • (The link really isn’t presentation-friendly)

  13. What the DbContext? • DbContext • Inherits from ObjectContext • Lightweight context for database • DbSet • Inherits from ObjectSet • Lightweight version • Fewer options to choose from

  14. Convention over Configuration • public class MyAppContext : DbContext • Default Connection String: “MyAppContext” • Creates database if one doesn’t exist • Default database order: SQL Express, SQLCE, SQL Server • DbSet<User> Users { get; set; } • Maps to “Users” table • Id (int) • Marked as primary key • identity column • Stored as UserIdin Users table

  15. Associations • One-To-Many • Users have many posts • publicvirtualICollection<Post> Posts { get; set; } • Posts have many comments • publicICollection<Comment> Comments { get; set; }

  16. Associations • One-to-One • Comments have an author (User) • publicvirtualUser Author {get; set;}

  17. Associations • Many-To-Many • Posts can contain many Tags • publicvirtualICollection<Tag> Tags { get; set; } • Tags can be applied to many posts • publicvirtualICollection<Post> Posts { get; set; }

  18. Lazy Loading • Standard Loading • public class user • publicICollection<Post> Posts { get; set; } • Lazy Loading • public class User • publicvirtualICollection<Post> Posts { get; set; }

  19. Database generation • Turning it off • You can turn it off • Database Initialization (IDatabaseInitializer) • DropCreateDatabaseAlways • CreateDatabaseIfNotExists • DropCreateDatabaseIfModelChanges • Better Migration support is supposed to be coming!

  20. Seeding Data • In your Database Initializer class: • protectedoverridevoidSeed(DatabaseContext context) • Useful for testing • Specify connection string + DropCreateDatabaseAlways= consistency + isolation

  21. Complex Types • Complex type = entity with no key • Automatic registration of a complex type: • No key can be inferred through convention • No primary key annotation / fluent API • Explicit registration of a complex type: • [ComplexType] annotation • ComplexType<>() Fluent API • Restrictions • Values must be scalar (no referencing allowed!) • Must be initialized in parent entity

  22. Overriding Convention • Examples • Change database connection string / name • publicCodeBookContext() : base("SocialNotWork") • Change table names • [Table("CaptchaType", SchemaName = "sec")]publicclassCaptchaTypeTest • Field mapping • [Column(Name="CaptchaTypeID", Order=1)]publicintCaptchaID { get; set; }

  23. Validation • Validation via ValidationAttribute(s) • [StringLength] • [Required] • [MaxLength] • [RegularExpression] • Entity or ComplexType validation • Honors IValidatableObject interface • Validating • Context.SaveChanges() invokes automatically • Get validation errors with Context.GetValidationErrors()

  24. Data Annotations • More Annotations • ForeignKey • ConcurrencyCheck • Required • Class-level • ComplexType • Table • Assembly • System.ComponentModel.DataAnnotations • Annotations • Key • MaxLength • MinLength • Column • StringLength • InverseProperty • NotMapped

  25. Inheritance Mapping • Impedance mismatch: OO vs. Relational design • “is a” vs. “has a”: Bridge the gap! • Three types of Inheritance Mapping • Table Per Hierarchy (TPH) • Table Per Type (TPT) • Table Per Concrete Class (TPC) • Which one should I use? • That depends…

  26. Table Per Hierarchy (TPH) • Table Per Hierarchy (TPH) • Use one table for all types (denormalize schema) • Class type determined by “Discriminator” • Discriminator value can be overridden for values and data types • This is the default convention • Cons • (DBA starts to yell at you because…) • Sub-class fields not enforced in database (NOT NULL) • Violates 3NF • Sub-class values dependent on Discriminator value

  27. Table Per Type (TPT) • Table Per Type (TPT) • Base table for base class • One table per derived type (differential) • Implementation • Table annotation on subtypes • fluent API via ToTable • Cons • Ugly generated SQL when querying for base class • Reporting more difficult due to normalized structure

  28. Table Per Concrete Class (TPC) • Table Per Concrete Class (TPC) • No base table for base class • One table per type contains all information • No VS2010 EDM designer support; EF runtime support • Implementation • One table per concrete type, no column sharing • No relationships; database is unaware • Fluent API: MapInheritedProperties() + ToTable() • Cons • Difficult migration / change process

  29. Inheritance Mapping • Which one should I use? • TPH • Behavior (not structure) is main differentiator of sub-classes • TPT • Structure (not behavior) is main differentiator of sub-classes • TPC • Base class rarely/never directly queried (for top level) • Query of concrete objects is high/the norm • Can use more than one method in a hierarchy • TPT vs. TPC – JOIN vs. UNION

  30. We also call these opportunities… • Drawbacks • (no) Stored procedure support • (no) Generation of classes from existing database (Code First stack) • (no) Enums (future release, not in EF at all) • WCF Data Services hack (not sure if issue still) • Internationalization conventions (maybe for RTW)

  31. EF4 Code First Workaround ideas • The “stored procedure” issue • Start out with EF Code First • Circle the wagon when stored procedures / other features are needed • Database First, refine model, generate POCO classes • WCF Data Services • Wait for RTM (if the problem still exists in CTP5) • Creativity is key! Share / monetize your ideas!

  32. Summary • EF: I have an idea (about what it is) • EF Code First – code wags database • Convention over configuration = efficiency + flexibility • Inheritance Mapping tackles OO/Relational impedance mismatch • Not perfect • EF Code First not done (as of 2/18) • Availability by end of Q1 2011

  33. You can Dig Deeper with these Handy Resources • Entity Framework FAQ • EF Design blog • ADO.NET team blog • EF on MSDN Library • EF on MSDN Data Development Center • Julie Lerman’s blog • Scott Guthrie’s blog • Scott Hanselman’s blog • MortezaManavi’s blog • The Morning Brew (Developer News)

  34. If you remember one thing from this presentation:

  35. Cycling is the new “Golf” Tallan, Inc. Proprietary and Confidential. Copyright 2010.

  36. WCF Data Services Bonus Slides Section #1

  37. Architecture Overview :WCF Data Services

  38. Open Data Protocol (OData) • Definition • OData enables you to expose your data as resources that are addressable by URIs • Enables you to access and change data by using the semantics of representational state transfer (REST) • Standard HTTP verbs supported: • GET, PUT, POST, DELETE. Reference: WCF Data Services Overview - http://msdn.microsoft.com/library/cc668794.aspx

  39. Output Formats – WCF Data Services • Atom • JSON • XML

  40. Freedom of data source – WCF Data Services • Entity Framework Provider • Uses Entity Data Models to structure access • Reflection Provider • Exposes data structures with interface IQueryable • Create/Update/Delete with interface IUpdatable • Custom Provider • Roll your own • Link to WCF Data Services Providers • http://msdn.microsoft.com/en-us/library/dd672591.aspx

  41. Override Configuration Bonus Slides Section #2

  42. Fluent API: Model Configuration • Relationships • One to Many • Many to One • Turn off cascade delete • Composite foreign key • Rename FK • Rename Many:Many cols • Mapping (Table, Cols) • Change names • Inheritance • Link to Fluent API page • Primary Keys • Simple or Composite • Properties • CLR-Nullable to required • Override string length • Switch off identity • Ignore property • Types • Complex Type

  43. Changing conventions • It can be done • Factory classes for conventions just need to be rerouted to other classes (or something)

More Related